一、mysql 数据库目录下找 connector/j 复制里面的 bin.jar文件
二、复制到Java目录下的lib文件夹下
三、在项目下创建一个文件下,将bin.jar 文件复制进去
四、创建项目 在eclipse窗口windows–preferences–build path —user libiraies—add jars
五、在项目上右键 Java buildpath–configurebuidpath–libraies–add jars
注意:四和五都从 项目的文件夹下选择
连接时的代码细节:
代码:
import java.sql.*;
public class studentscore {
//一、把dirver、url、user、password声明为private static。并且填好值
private static String driver = "com.mysql.cj.jdbc.Driver"; //驱动
//url。下面的“studentscore”是库名,可以根据个人需求“私人订制”
private static String url = "jdbc:mysql://localhost:3306/studentscore?useSSL=false&serverTimezone=UTC";
private static String user = "root"; //用户
private static String password = "root123123"; //密码
public static void main(String[] args) {
//二、我们就要通过Connection conn、PreparedStatement ps、ResultSet rs 这三个基本的SQL类完成基本操作
Connection conn = null; //连接
PreparedStatement ps=null; //处理命令
ResultSet rs=null; //结果集
String selectSql="select * from student where dept=?"; //?代表动态的数据
String insertSql="insert into student(sNo,sName,sex,age,dept) values(?,?,?,?,?)";
String updateSql="update student set dept='金融' where sNo=?";
String deleteSql="delete from student where sNo=?";
try {
//三、通过Class.forName(dirver) 接收驱动
Class.forName(driver); //动态类加载
//四、通过conn接收DriverManager.getConnection(url,user,password)的返回值、
conn=DriverManager.getConnection(url,user,password);//驱动管理器(DriverManager)
//五、通过ps conn.preparedStatement(SQL语句)的返回值
ps=conn.prepareStatement(selectSql); //处理命令
//六、通过ps.setXxxx(int index,Xxxx)来设置SQL语句中的自定义变量
ps.setString(1, "计算机"); //1代表第一个“?”,“计算机”代表第一个?的值
//七、通过相应的变量 接收 ps.executeXxxx()的执行结果既SQL语句的执行结果
rs=ps.executeQuery();//执行查询
while(rs.next()) { //rs.next()的返回值来判断rs中是否还有值
//因为是一个查询操作所以getXxx()方法获取到查询的结果
String no =rs.getString("sNo");
String name =rs.getString("sName");
String sex =rs.getString("sex");
int age =rs.getInt("age");
String dept =rs.getString("dept");
System.out.println(no+"\t"+name+"t"+sex+"\t"+age+"\t"+dept);
}
ps=conn.prepareStatement(insertSql);
ps.setString(1, "201201011");
ps.setString(2, "小六");
ps.setString(3, "男");
ps.setInt(4, 18);
ps.setString(5, "计算机");
int count=ps.executeUpdate(); //执行更新;注意executeXxxx()
System.out.println("添加"+count+"条记录到Student表中");
ps=conn.prepareStatement(updateSql);
ps.setString(1, "201201009");
count=ps.executeUpdate(); //执行修改;注意executeXxxx()
System.out.println("修改了Student表中"+count+"条记录");
ps=conn.prepareStatement(deleteSql);
ps.setString(1,"201201008");
count=ps.executeUpdate(); //执行删除;注意executeXxxx()
System.out.println("删除了Student表中"+count+"条记录");
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
finally {
try {
if(rs!=null) rs.close(); //最后是要将这三个操作关闭的。当然也会报异常,所以try-catch包裹一下就行
if(ps!=null) ps.close();
if(conn!=null) conn.close();
} catch (Exception e2) {
// TODO: handle exception
e2.printStackTrace();
}
}
}
}