Today suddenly a whim, want to connect MySQL with Java, remember before is in VS2010 environment with C # Connection SQL Sever, in fact, their methods are similar.
Now it's easy to explain how Java connects to MySQL.
The first step , the design of MySQL database, design database when special note, database name is xsxx, table name is XS. Note that when you set the character, you must choose UTF8, or you will not understand the form of appearance.
Second Step : New project in Esclip, project name is TESTJDBC, new class name is TESTJDBC, add Reference project file
Step three : Related code in the project:
——————————————————————————————————————————————————————————————————
/*****
* Java connection MySQL
* @author Yanlong
*2017/5/7
*/
Import java.sql.Connection;
Import Java.sql.DriverManager;
Import Java.sql.ResultSet;
Import java.sql.Statement;
Import java.util.Collection;
Import java.sql.SQLException;
Import javax.sql.Statement;
public class Testjdbc {
public static void Main (string[] args) {
ResultSet Rs=null;
Statement Stmt=null;
Connection Conn=null;
try{
/* Load and register the JDBC driver for MySQL */
Class.forName ("Com.mysql.jdbc.Driver");
/* Establish a connection to MySQL */
Conn=drivermanager.getconnection ("Jdbc:mysql://localhost:3306/xsxx", "root", "123456");
/* Access the database and execute the SQL statement */
Stmt=conn.createstatement ();
Rs=stmt.executequery ("Select *from xs");
while (Rs.next ()) {
System.out.println (Rs.getint ("id"));
System.out.println (rs.getstring ("name"));
System.out.println (Rs.getstring ("major"));
}
}catch (ClassNotFoundException e) {
E.printstacktrace ();
} catch (SQLException e) {
TODO auto-generated Catch block
E.printstacktrace ();
}finally{
try{
if (rs!=null) {
Rs.close ();
Rs=null;
}
if (stmt!=null) {
Stmt.close ();
Stmt=null;
}
if (conn!=null) {
Conn.close ();
Conn=null;
}
}catch (SQLException e) {
E.printstacktrace ();
}
}
}
}
————————————————————————————————————————————————————————————
Fourth step: directly run the project, the effect of running:
Java connection to MySQL process