The connection should be aware of all jars, as well as the environment to build;
Package util;
Import Java.sql.DriverManager;
Import Java.sql.ResultSet;
Import java.sql.SQLException;
Import com.mysql.jdbc.Connection;
Import com.mysql.jdbc.Statement;
public class Jdbc {
public static void Main (string[] args) {
Driver name
String Driver = "Com.mysql.jdbc.Driver";
The URL points to the database name you want to access Scutcs
String url = "Jdbc:mysql://127.0.0.1:3306/golden";
User name when MySQL is configured
String user = "root";
Java password when connecting to MySQL configuration
String password = "1234";
try {
Load Driver
Class.forName (driver);
Continuous database
Connection conn = (Connection) drivermanager.getconnection (URL, user, password);
if (!conn.isclosed ())
System.out.println ("Successfully connected! ");
statement used to execute SQL statements
Statement Statement = (Statement) conn.createstatement ();
The SQL statement to execute
String sql = "SELECT * from Golden.users";
Result set
ResultSet rs = statement.executequery (SQL);
System.out.println ("----------------------------------");
System.out.println ("Execution results are as follows:");
System.out.println ("----------------------------------");
System.out.println ("UserSID" + "\ T" + "usersname" + "\ T" + "pwd" + "\ T" + "age");
System.out.println ("----------------------------------");
String usersname = null;
String Pwd=null;
Integer age=0;
while (Rs.next ()) {
Select data
Usersname = rs.getstring ("Usersname");
Pwd=rs.getstring ("pwd");
Age=rs.getint (4); Index, also available as age;
Output results
system.out.println (rs.getstring ("UserSID") + "\ T" + usersname+ "\ T" + pwd+ "\ T" + age);
}
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 ();
}
}
}