How to connect Java to the MySQL database
How to connect Java to the MySQL database
Download: mysql-connector-java-5.1.38.tar.gz
Http://dev.mysql.com/downloads/connector/j/
Tar zxvf mysql-connector-java-5.1.38.tar.gz
Decompress the package
Bkjia @ Ubuntu :~ /Downloads $ cd./mysql-connector-java-5.1.38/
Bkjia @ ubuntu :~ /Downloads/mysql-connector-java-5.1.38 $ ls
Build. xml COPYING mysql-connector-java-5.1.38-bin.jar README.txt
CHANGES docs README src
Bkjia @ ubuntu :~ /Downloads/mysql-connector-java-5.1.38 $ sudo cp mysql-connector-java-5.1.38-bin.jar/home/tomcat/lib
[Sudo] password for bkjia:
Add External JARs
Code:
Import java. SQL .*;
Publicclass JDBCTest {
Publicstaticvoid main (String [] args ){
// Driver name
String driver = "com. mysql. jdbc. Driver ";
// The URL points to the name of the database to be accessed bookstore
String url = "jdbc: mysql: // 127.0.0.1: 3306/bookstore ";
// Username for MySQL Configuration
String user = "root ";
// MySQL password
String password = "password ";
Try {
// Load the driver
Class. forName (driver );
// Continuous Database
Connection conn = DriverManager. getConnection (url, user, password );
If (! Conn. isClosed ())
System. out. println ("Succeeded connecting to the Database! ");
// Statement is used to execute SQL statements
Statement statement = conn. createStatement ();
// SQL statement to be executed
String SQL = "select * from books ";
// Result set
ResultSet rs = statement.exe cuteQuery (SQL );
System. out. println ("-----------------");
System. out. println ("the execution result is as follows :");
System. out. println ("-----------------------------------------------");
System. out. println ("ISBN" + "\ t" + "author" + "\ t" + "bookname" + "\ t" + "bookname ");
System. out. println ("-----------------------------------------------");
String name = null;
While (rs. next ()){
// Select the ISBN Column
Name = rs. getString ("ISBN ");
// System. out. println (name );
// First, use the ISO-8859-1 character set to decode the name into a byte sequence and store the result in a new byte array.
// Then use the GB2312 character set to decode the specified byte array
Name = new String (name. getBytes ("ISO-8859-1"), "GB2312 ");
// Output result
System. out. println (name + "\ t" + rs. getString ("author") + "\ t" + rs. getString ("bookname") + "\ t" + "\ t" + rs. getString ("price "));
}
Rs. close ();
Conn. close ();
} Catch (ClassNotFoundException e ){
System. out. println ("Sorry, can't find the Driver! ");
E. printStackTrace ();
} Catch (SQLException e ){
E. printStackTrace ();
} Catch (Exception e ){
E. printStackTrace ();
}
}
}
Output:
Succeeded connecting to the Database!
-----------------
The execution result is as follows:
-----------------------------------------------
ISBN author bookname
-----------------------------------------------
123456 bkjia java 23.40
234567 bkjia C ++ 34.60
This article permanently updates the link address: