JDBC 的大体步骤:
1:导入架包
2:创建连接
3.通过连接的方法preparedstatement 创建声明,声明的参数就是你需要执行的 SQL语句
4.关闭声明,关闭连接
注意事项:
1."jdbc:mysql:///database1?user=root&password=666"
参数传jdbc:数据库类型///数据库名称?用户名(key)=(value)=&密码(key)=(value)
2.查询操作的 Student 报错 你得先创建一个 Student类 id,name get set 方法 ,重写 ToString 方法
主要单词:
1.connection 连接
2.driver manager驱动程序管理器
3.prepare statement 编辑表
4.resultset 结果集
增删改查的具体操作如下:
//增
public static void inster() throws ClassNotFoundException, SQLException {
Class.forName("com.mysql.jdbc.Driver");
//通过DriverManager建立连接 参数传jdbc:数据库类型///数据库名称?用户名(key)=(value)=&密码(key)=(value)
Connection connection= DriverManager.getConnection("jdbc:mysql:///database1?user=root&password=666");
//通过连接的 prepareStatement 的方法创建声明 参数传入要执行的 sql 语句
PreparedStatement statement=connection.prepareStatement("INSERT INTO student VALUE(?,?);");
//sql 传入的参数可以用?代替
//根据参数的类型和问号的位置这个是int类型的第一个问号
statement.setInt(1,11);
//这个是第二个问号 string 类型的
statement.setString(2,"harry");
//执行更新 这句代码执行才有效
statement.executeUpdate();
//关闭声明
statement.close();
//关闭连接
connection.close();
}
//改
public static void update() throws ClassNotFoundException, SQLException {
Class.forName("com.mysql.jdbc.Driver");
Connection connection=DriverManager.getConnection("jdbc:mysql:///database1?user=root&password=666");
PreparedStatement statement=connection.prepareStatement("UPDATE student SET name=? WHERE id=?;");
statement.setString(1,"harry");
statement.setInt(1,12) ;
statement.executeUpdate();
statement.close();
connection.close();
}
//删
public static void delete() throws ClassNotFoundException, SQLException {
Class.forName("com.mysql.jdbc.Driver");
Connection connection=DriverManager.getConnection("jdbc:mysql:///database1?user=root&password=666");
PreparedStatement statement=connection.prepareStatement("DELETE FROM student WHERE name=?");
statement.setString(1,"harry");
statement.executeUpdate();
statement.close();
connection.close();
}
//查
public static void select() throws ClassNotFoundException, SQLException{
Class.forName("com.mysql.jdbc.Driver");
Connection connection=DriverManager.getConnection("jdbc:mysql:///database1?user=root&password=666");
PreparedStatement statement=connection.prepareStatement("Select * from student");
//声明(statement)的方法执行查询的结果存入结果集(resultSet);
ResultSet resultSet=statement.executeQuery();
//创建集合arrayList
ArrayList<Student> arrayList=new ArrayList();
//while 循环 如果结果集不为空执行
while(resultSet.next())
{
//创建 student类 存储 sql 查询的student值
Student student=new Student(
//结果集(resultSet)获取一行中第一个位置的值 id 转换成int类型 获取一行中第二个位置的值 name 转换成String类型
(int)resultSet.getObject(1),(String)resultSet.getObject(2));
//把创建的 student保存着 sql 里student 的值得添加到 arrays
arrayList.add(student);
}
statement.close();
connection.close();
//打印 arraylist 把创建的 Student类里重写toString 方法
System.out.println(arrayList);
}