在连接数据库之前得下载JDBC-MySQL数据库驱动, 可以登录MySQL的官方网站www.mysql.com后,我这个用的是mysql-connector-java-5.1.40.zip,将该zip解压之后,将该驱动复制到JDK的扩展目录中(即JAVA-HOME环境变量指定的JDK),
JAVA连接数据库的相关代码:
package example1;
import java.sql.*;
public class connection {
public static void main(String args[]) {
Connection con = null;
//PreparedStatement sql = null;
Statement sql;
ResultSet rs;
String uri = "jdbc:mysql://localhost:3306/students?useSSL=true";
String user = "root";
String password = "root";
try {
Class.forName("com.mysql.jdbc.Driver");//加载JDBC-MySQL驱动
System.out.println("驱动加载成功");
}
catch (ClassNotFoundException e) { }
try {
con = DriverManager.getConnection(uri,user,password);//连接代码
System.out.println("连接成功");
}
catch(Exception e) {
e.printStackTrace();
}
try {
//sql = con.prepareStatement("SELECT * FROM mess");
sql = con.createStatement();
//rs = sql.executeQuery(); //查询mess表
rs = sql.executeQuery("SELECT * FROM MESS");//查询mess表
while(rs.next()) { //ResultSet对象一次只能看到一个数据行,使用next()方法移到下一个数据行
/*String number = rs.getString(1);
String name = rs.getString(2);
Date date = rs.getDate(3);
float height = rs.getFloat(4);
System.out.printf("%s\t",number);
System.out.printf("%s\t",name);
System.out.printf("%s\t",date);
System.out.printf("%.2f\t",height);*/
}
con.close();//关闭连接
}
catch(Exception e) {
e.printStackTrace();
}
}
}
将数据库连接的代码单独封装在一个GetDatabaseConnection类中,以后用的时候可以直接拿来用。
import java.sql.*;
public class GetDBConnection {
public static Connection connectDB(String DBName,String id,String p) {
Connection con = null;
String uri = "jdbc:mysql://localhost:3306/"+
DBName+"?UseSSL=true&characterEncoding=utf-8";
try {
Class.forName("com.mysql.jdbc.Driver");//加载驱动
}
catch(Exception e) { }
try {
con = DriverManager.getConnection(uri, id, p);//连接
}
catch(SQLException e) { }
return con;
}
}