Import java.sql.Connection;
Import Java.sql.DriverManager;
Import Java.sql.ResultSet;
Import java.sql.SQLException;
Import java.sql.Statement;
public class Mysqlconnection {
public static void Main (string[] args) {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
String URL = null;
String user = null;
String password = null;
String sql = null;
try {
Class.forName ("Com.mysql.jdbc.Driver"); Load MYSQ Driver
} catch (ClassNotFoundException e) {
SYSTEM.OUT.PRINTLN ("Driver loading error");
E.printstacktrace ();//Print Error details
} try {
URL =
"Jdbc:mysql://localhost/test?user=root&password=yqs2602555&useunicode=true&&characterencoding= Gb2312&autoreconnect = true ";//simple notation: url =" jdbc:myqsl://localhost/test (database name)? User=root (user) &password=yqs2602555 (password) "; user = "Root";
Password = "yqs2602555";
conn = Drivermanager.getconnection (Url,user,password);
} catch (SQLException e) {
SYSTEM.OUT.PRINTLN ("Database link error");
E.printstacktrace ();
}
try {
stmt = Conn.createstatement ();
sql = "SELECT * from dept";//dept This table has three fields of deptno,deptname and age
rs = stmt.executequery (sql);//Execute SQL statement
while (Rs.next ()) {
System.out.print (Rs.getint ("deptno") + "");
System.out.print (rs.getstring ("deptname") + "");
System.out.println (Rs.getint ("age") + "");
}
} catch (SQLException e) {
SYSTEM.OUT.PRINTLN ("Data manipulation error");
E.printstacktrace ();
}//shutting down the database
try {
if (rs! = null) {
Rs.close ();
rs = null;
}
if (stmt! = null) {
Stmt.close ();
stmt = null;
}
IF (conn! = null) {
Conn.close ();
conn = null;
}
} catch (Exception e) {
SYSTEM.OUT.PRINTLN ("Database shutdown error");
E.printstacktrace ();
}
}
The results of the operation are as follows: 1 Yqs 0
2 Hello 0
3 Yqsshr 0
4 World 0
5 Hryspa 0
1 Yqs 0
2 Hello 0
3 Yqsshr 0
4 World 0
5 Hryspa 0
1 YQS11 21
1 YQS21 31
1 YQS31 41
1 YQS41 51
A classic JDBC connection to MySQL program