
正文
增删改查-java(新手)
提示:扫一扫查出行【扫一扫了解最新限行尾号】
复制提示
PreparedStatement:
方法:
Connection:
方法:
实例:
1、查询:
package cn.chuang.JdbcDome;
import java.sql.*;
public class JdbcDome3 {
public static void main(String[] args) throws Exception {
PreparedStatement ppst = null;
Connection conn = null;
fun3(ppst,conn);
}
public static void fun1(PreparedStatement ppst,Connection conn) throws Exception {
//查询表的内容
//1 注册驱动 获得Connection
Class.forName("com.mysql.jdbc.Driver");
//2 获得链接
conn = DriverManager.getConnection("jdbc:mysql:///semployee", "root", "root");
//3 sql语句
String sql = "select * from lll";
//4 获得执行sql语句的对象
ppst = conn.prepareStatement(sql);
ResultSet rs = ppst.executeQuery(sql);
//5 让游标向下移动一行
rs.next();
int i = rs.getInt(1);
String name = rs.getString("ename");
//6 获取数据
System.out.println(i+" "+name);
}
2、添加
public static void fun2(PreparedStatement ppst,Connection conn) throws Exception {
//在表中添加数据,表结构有多少就要写多少。不能漏写,会报错。
try {
//1 注册驱动 获得Connection
Class.forName("com.mysql.jdbc.Driver");
//2 获得链接
conn = DriverManager.getConnection("Jdbc:mysql:///semployee", "root", "root");
//3 sql语句
String sql = "insert into lll values (null,'兀立扗'),(null,'吴诗意')";
//4 获得执行sql语句的对象
ppst = conn.prepareStatement(sql);
int i = ppst.executeUpdate(sql);
//5 处理结果
System.out.println(i);
//6 另创建if语句,做提示用。
if (i>0){
System.out.println("添加成功");
}else{
System.out.println("添加失败");
}
} catch (Exception e) {
e.printStackTrace();
}finally {
if(ppst!=null){
try {
ppst.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn!=null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
3、删除
public static void fun3(PreparedStatement ppst,Connection conn) throws Exception {
//删除表内数据。
//1 注册驱动 获得Connection
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql:///semployee", "root", "root");
//2 sql语句
String sql = "delete from lll where uid = 2";
//3 获得执行sql语句的对象Statement
ppst = conn.prepareStatement(sql);
int i = ppst.executeUpdate(sql);
//4 处理结果
System.out.println(i);
if (i>0){
System.out.println("删除成功");
ppst.close();
conn.close();
}else{
System.out.println("删除失败");
}
}
4、修改
public static void fun4(PreparedStatement ppst,Connection conn) throws Exception {
//修改表内数据
//1 注册驱动。
Class.forName("com.mysql.jdbc.Driver");
//2 链接数据库。
conn = DriverManager.getConnection("jdbc:mysql:///semployee", "root", "root");
//3 SQL语句。
String sql = "update lll set uname = '吴惆' where uid = 1 ";
//4 获得执行SQL的语句。
ppst = conn.prepareStatement(sql);
//5 处理结果。
int ou = ppst.executeUpdate(sql);
System.out.println(ou);
}
}








