8.0要写的版本
package test;
import java.sql.*;
public class SqlHelper {
//mysql驱动包名
private static final String DRIVER_NAME = "com.mysql.cj.jdbc.Driver";
//数据库连接地址
private static final String URL = "jdbc:mysql://localhost:3306/kk?useSSL=false&serverTimezone=GMT" +
"&allowPublicKeyRetrieval=true";
//用户名
private static final String USER_NAME = "joker";
//密码
private static final String PASSWORD = "123456789";
public static Connection Getconnection() {
Connection connection = null;
try {
//加载mysql的驱动类
Class.forName(DRIVER_NAME);
//获取数据库连接
connection = DriverManager.getConnection(URL, USER_NAME, PASSWORD);
} catch (Exception e) {
e.printStackTrace();
System.out.println("没有成功连接");
}
return connection;
}
public ResultSet SqlRead(String sql, String[] parameter) {
Connection connection = null;
PreparedStatement pr = null;
ResultSet rs = null;
try {
//获取数据库连接
connection = Getconnection();
//mysql查询语句
pr = connection.prepareStatement(sql);
if (parameter.length > 0) {
for (int i = 0; i < parameter.length; i++) {
pr.setString(i + 1, parameter[i]);
}
}
//结果集
rs = pr.executeQuery();
//打印数据的信息
while (rs.next()) {
System.out.println(rs.getString(1));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
Closesql(connection, pr, rs);
}
return rs;
}
//关闭数据库
public static void Closesql(Connection connection, PreparedStatement pr, ResultSet rs) {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (pr != null) {
try {
pr.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public boolean SqlUpdate(String sql, String[] parameter) {
boolean result = false;
Connection connection = null;
PreparedStatement pr = null;
ResultSet rs = null;
try {
//获取数据库连接
connection = Getconnection();
//mysql查询语句
pr = connection.prepareStatement(sql);
if (parameter.length > 0) {
for (int i = 0; i < parameter.length; i++) {
pr.setString(i + 1, parameter[i]);
}
}
int num = pr.executeUpdate();
if (num > 0) {
result = true;
System.out.println("数据更新成功");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
Closesql(connection, pr, rs);
}
return result;
}
}
package test;
public class Demo11 {
public static void main(String[] args){
//这个是数据的查找
String sql="select * from cc where id=?";
SqlHelper sqlHelper=new SqlHelper();
String []parameter={"4"};
sqlHelper.SqlRead(sql,parameter);
//这个是数据的更新
sql="insert into cc values(?,?,?)";
String []kk={"kk","7","78"};
sqlHelper.SqlUpdate(sql,kk);
}
}
8.0使用的是com.mysql.cj.jdbc.Driver,5.0使用的是com.mysql.jdbc.Driver。
不仅如此,还有时区的限制,URL 里面也有很多要添加的东西
//mysql驱动包名
private static final String DRIVER_NAME = "com.mysql.cj.jdbc.Driver";
// //数据库连接地址
private static final String URL = "jdbc:mysql://localhost:3306/kk?useSSL=false&serverTimezone=GMT" +
"&allowPublicKeyRetrieval=true";
因为mysql 版本的更新,以前的视频就有些不管用。