- Saved searches
- Use saved searches to filter your results more quickly
- jkaninda/crud
- Name already in use
- Sign In Required
- Launching GitHub Desktop
- Launching GitHub Desktop
- Launching Xcode
- Launching Visual Studio Code
- Latest commit
- Git stats
- Files
- README.md
- About
- Русские Блоги
- Android -приложение Kotlin Language Connect MySQL База данных
- Android -приложение Kotlin Language Connect MySQL База данных
- Статьи Справочник
- Предисловие
- 1. Подготовка окружающей среды
- Во -вторых, код проекта
- 1. Создать инженерную инженерию
- 2. Импорт пакет JAR
- 3. Настройте разрешения сети
- 4. Файл макета страницы
- 5. Активность код
- Подвести итог
- How to Connect to MySQL Database from Kotlin using JDBC?
- Step 1 : Add MySQL connector for java
- Step 2 : Establish a connection to MySQL Server
- Step 3 : Execute MySQL Query to show DATABASES available
- Example 1 – Connect to MySQL Database from Kotlin using JDBC
- Conclusion
Saved searches
Use saved searches to filter your results more quickly
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.
Android Kotlin Mysql Library
jkaninda/crud
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Sign In Required
Please sign in to use Codespaces.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching Xcode
If nothing happens, download Xcode and try again.
Launching Visual Studio Code
Your codespace will open once ready.
There was a problem preparing your codespace, please try again.
Latest commit
- addition of possibility of canceling and stop requests
Git stats
Files
Failed to load latest commit information.
README.md
Android kotlin Mysql Library
repositories> repository> id>jitpack.io/id> url>https://jitpack.io /repository> /repositories> dependency> groupId>com.github.jkanTech/groupId> artifactId>CrudartifactId> version>1.0.1/version> /dependency>
repositories < maven < url "https://jitpack.io" > > dependencies < implementation 'com.github.jkantech:crud:1.0.2' >
- Download the latest version of the API
- Unzip it in your server directory
- Go to the api/query/v1/database folder
- Open the config.php file
- Put the database username, password and database name
$DB_USER pl-s">root";//Data base user $DB_PASS pl-s">root"; // Date base user pass $DB_DATABASE pl-s">crudexample"; //Data base name
repositories < maven < url "https://jitpack.io" > > dependencies < implementation 'com.github.jkantech:crud:1.0.2' >
uses-permission android:name="android.permission.INTERNET"/> application android:usesCleartextTraffic="true"
private fun getAll()< val crud=Crud(this,"http://192.168.8.101/api/query/v1/") crud.get("users",null,object :OnResponseListener< override fun onError(error: String?) < toastMessage(requireContext(),"Error") > //on response override fun onResponse(response: String?) < toastMessage(requireContext(),response.toString()) >>) >
private fun getUser()< //get : table,condition val crud=Crud(this,"http://192.168.8.101/api/query/v1/") //Get Users with where condition val conds=JSONObject() try < conds.put("id",2) >catch (e:JSONException) < e.printStackTrace() >crud.get("users", conds, object : OnResponseListener< override fun onError(error: String?) < TODO("Not yet implemented") > override fun onResponse(response: String?) < TODO("Not yet implemented") > >) >
private fun updateUser(id:Int,name:String,first_name:String,email:String)< val crud=Crud(this,"http://192.168.8.101/api/query/v1/") val data=JSONObject() val conds=JSONObject() try < //Condition conds.put("id",id) //Rows and Values data.put("user_name",name) data.put("first_name",first_name) data.put("user_email",email) >catch (e:JSONException) < e.printStackTrace() >crud.set("users",data,conds,object :OnResponseListener< override fun onError(error: String?) < toastMessage(requireContext(),"Error") > //on response override fun onResponse(response: String?) < toastMessage(requireContext(),response.toString()) >>) >
Download the Crud Example App or look at the source code.
This project is licensed under the Apache License 2.0 — see the LICENSE file for details.
About
Android Kotlin Mysql Library
Русские Блоги
Android -приложение Kotlin Language Connect MySQL База данных
Android -приложение Kotlin Language Connect MySQL База данных
Совет: после написания статьи каталог может быть сгенерирован автоматически. Как генерировать справочный документ справа
Статьи Справочник
Предисловие
В этом семестре есть курс, разработанный Android App, и дизайн учебного плана будет проведен на следующей неделе.
Поскольку я хочу создать онлайн -приложение, я хочу подключиться к базе данных на облачном сервере; я долгое время нашел статью и, наконец, нашел статью и реализовал эту функцию. Настоящим я записываю ее.
Справочная статья:lhttps://www.jianshu.com/p/681dfc6d113f.
Совет: Ниже приведен текст этой статьи, можно использовать следующие случаи для справки
1. Подготовка окружающей среды
Во -вторых, код проекта
1. Создать инженерную инженерию
2. Импорт пакет JAR
build.gradle:
dependencies ... implementation files('libs/mysql-connector-java-5.1.47.jar') >
3. Настройте разрешения сети
manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.cmysql"> uses-permission android:name="android.permission.INTERNET" /> application> ... /application> /manifest>
4. Файл макета страницы
?xml version="1.0" encoding="utf-8"?> LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Hello World!" android:id="@+id/tv_hello" /> /LinearLayout>
5. Активность код
package com.example.cmysql import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.util.Log import kotlinx.android.synthetic.main.activity_main.* import java.sql.Connection import java.sql.DriverManager import java.sql.SQLException class MainActivity : AppCompatActivity() override fun onCreate(savedInstanceState: Bundle?) super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) tv_hello.setOnClickListener Thread(Runnable val sql = "SELECT * FROM users" mysqlConnection(sql) >).start() > > /** * Подключиться к базе данных */ fun mysqlConnection(sql:String) var cn: Connection try // загрузить драйвер Class.forName("com.mysql.jdbc.Driver") // установить связь cn = DriverManager.getConnection("jdbc:mysql://39.99.141.184:3306/jdbc", "ccsu", "123456") val ps = cn.createStatement() val resultSet = ps!!.executeQuery(sql) while (resultSet.next()) Log.d("mysqlConnection: " , resultSet.getString("id") + resultSet.getString("name") + resultSet.getString("password")+resultSet.getString("email")) > if (ps != null) ps!!.close() > if (cn != null) cn.close() > > catch (e: ClassNotFoundException) e.printStackTrace() > catch (e: SQLException) e.printStackTrace() > > >
Подвести итог
Этот проект только реализует доступ к базе данных MySQL и данным запросов. Другие другие функции могут быть реализованы в соответствии с самостоятельными.
How to Connect to MySQL Database from Kotlin using JDBC?
In this tutorial, we will learn how to connect to MySQL Database from Kotlin using JDBC with the help a Kotlin Example Program.
Following is a step by step process explained to connect to MySQL Database from Kotlin using JDBC.
Step 1 : Add MySQL connector for java
MySQL connector for java works for Kotlin as well. Download MySQL connector for java, mysql-connector-java-5.1.42-bin.jar , from [https://dev.mysql.com/downloads/connector/j/5.1.html]. Open IntelliJ IDEA, Click on File in Menu, Click on Project Structure, Click on Libraries on the left panel, and add the jar to Libraries.
Step 2 : Establish a connection to MySQL Server
To establish a connection to MySQL Server
- Prepare username and password as properties
- Use Class.forName() to create an instance for JDBC Driver.
- Use DriverManager.getConnection() to create a connection to the SQL server. The first argument to this function is the URL that specifies the location of MySQL server. The second argument has credentials to login to the server.
val connectionProps = Properties() connectionProps.put("user", username) connectionProps.put("password", password) try < Class.forName("com.mysql.jdbc.Driver").newInstance() conn = DriverManager.getConnection( "jdbc:" + "mysql" + "://" + "127.0.0.1" + ":" + "3306" + "/" + "", connectionProps) >catch (ex: SQLException) < // handle any errors ex.printStackTrace() >catch (ex: Exception) < // handle any errors ex.printStackTrace() >
Step 3 : Execute MySQL Query to show DATABASES available
var stmt: Statement? = null var resultset: ResultSet? = null try < stmt = conn. createStatement() resultset = stmt. executeQuery("SHOW DATABASES;") if (stmt.execute("SHOW DATABASES;")) < resultset = stmt.resultSet >while (resultset. next()) < println(resultset.getString("Database")) >> catch (ex: SQLException) < // handle any errors ex.printStackTrace() >
Example 1 – Connect to MySQL Database from Kotlin using JDBC
The following program connects to a specific MySQL server and executes ‘SHOW DATABASES;’ query.
import java.sql.* import java.util.Properties /** * Program to list databases in MySQL using Kotlin */ object MySQLDatabaseExampleKotlin < internal var conn: Connection? = null internal var username = "username" // provide the username internal var password = "password" // provide the corresponding password @JvmStatic fun main(args: Array) < // make a connection to MySQL Server getConnection() // execute the query via connection object executeMySQLQuery() >fun executeMySQLQuery() < var stmt: Statement? = null var resultset: ResultSet? = null try < stmt = conn. createStatement() resultset = stmt. executeQuery("SHOW DATABASES;") if (stmt.execute("SHOW DATABASES;")) < resultset = stmt.resultSet >while (resultset. next()) < println(resultset.getString("Database")) >> catch (ex: SQLException) < // handle any errors ex.printStackTrace() >finally < // release resources if (resultset != null) < try < resultset.close() >catch (sqlEx: SQLException) < >resultset = null > if (stmt != null) < try < stmt.close() >catch (sqlEx: SQLException) < >stmt = null > if (conn != null) < try < conn. close() >catch (sqlEx: SQLException) < >conn = null > > > /** * This method makes a connection to MySQL Server * In this example, MySQL Server is running in the local host (so 127.0.0.1) * at the standard port 3306 */ fun getConnection() < val connectionProps = Properties() connectionProps.put("user", username) connectionProps.put("password", password) try < Class.forName("com.mysql.jdbc.Driver").newInstance() conn = DriverManager.getConnection( "jdbc:" + "mysql" + "://" + "127.0.0.1" + ":" + "3306" + "/" + "", connectionProps) >catch (ex: SQLException) < // handle any errors ex.printStackTrace() >catch (ex: Exception) < // handle any errors ex.printStackTrace() >> >
information_schema mysql performance_schema studentsDB sys
Conclusion
In this Kotlin Tutorial, we have learnt to connect to MySQL Database from Kotlin using JDBC with the help of Kotlin Example Program.