Java Connection MySQL need driver package, can download the jar package provided by rookie Tutorial:Http://static.runoob.com/download/mysql-connector-java-5.1.39-bin.jar
The method of operation can be divided into three steps:
First, the configuration program--Let our program can find the database driver jar Package
1. Copy the. jar file to the project.
2. Right-click on the "Build path"-"Configure Build Path"-"library"-"Add external jar"-Find the drive jar of the database in the Eclipse project-click OK. "Referenced libraries" will appear in the left-hand package Explorer, where we can find the jar package we just imported
Ii. new databases and tables
1. Open MySQL, click "Connect" in the upper left corner, enter the connection name, OK. (The password can be empty)
2. Click the right mouse button on the established connection, select "CREATE Database", enter the database name in the popup window, select the character set: UTF8--UTF-8 Unicode
3. On the newly created database MyDB, double click on the left mouse button, the icon turns green, expand and click "CREATE TABLE"
4. Enter the relevant data and save it as input table name
5. Open the table, enter data, and close after input, will automatically save the data
Third, run the Java Connection database and make relevant operations
Divided into three steps
1. Load Data Access drivers
Class.forName ("Com.mysql.jdbc.Driver");
The "referenced library" appears in the left-hand package Explorer, where you can find the driver package
2. Connect to the data "library"
Connection conn = drivermanager.getconnection ("Jdbc:mysql://127.0.0.1:3306/mydb", "Root", "");
DriverManager: Driver Manager class, getconnection (URL, database login, password): How to get Connected
Jdbc:mysql://localhost:3306/mydb format origin
jdbc:mysql://Native Address: Port number/database name
To add Chinese characters to the database, the URL should read:
Jdbc:mysql://127.0.0.1:3306/mydb?characterencoding=gbk
3. Building the Execute SQL command
Statement state = Conn.createstatement ();
State.executeupdate ("Delete and change SQL statement");
State.executequery ("SQL statement for Query");
Conn.close ();//close connection
Example: Add student number to XS table: 008, Name: Li Li, school: four
ImportJava.sql.*; Public classTest2 { Public Static voidMain (string[] args)throwsException {//1. Load Data access DriversClass.forName ("Com.mysql.jdbc.Driver"); //2. Connect to the Data "library"Connection conn= drivermanager.getconnection ("Jdbc:mysql://localhost:3306/mydb?characterencoding=gbk", "Root", "" "); //3.Build SQL commandStatement state=conn.createstatement (); String s= "INSERT into XS values (' 008 ', ' Lily ', ' four ')"; State.executeupdate (s); }}
After the program runs, query table XS results, successful execution
Connect Java to MySQL.