jdbc实现数据全查
//查询全部数据
public static void PrintAll(){
try {
//创建驱动
Class.forName("com.mysql.jdbc.Driver");
//连接数据库
Connection conn=DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/lx?useSSL=true&characterEncoding=utf8","root","123456");
//写出sql语句
String sql="select * from user";
//选中语句并执行
PreparedStatement pstm = conn.prepareStatement(sql);
//产生结果集
ResultSet rs = pstm.executeQuery();
//处理结果
while (rs.next()){
System.out.println("用户编号:"+rs.getInt(1)+",用户名称:"+rs.getString(2)+
",用户密码"+rs.getString(3)+",用户类型"+rs.getInt(4));
}
//关闭连接
rs.close();
pstm.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
jdbc实现新增
public static void AddUser(){
try {
//创建驱动
Class.forName("com.mysql.jdbc.Driver");
//连接数据库
Connection conn=DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/lx?useSSL=true&characterEncoding=utf8","root","123456");
//写出sql语句
String sql="insert into user value (null,?,?,?)"; //?占位符,占的是空的位置,目的是放数据
//选中语句并执行
PreparedStatement pstm = conn.prepareStatement(sql);
System.out.println("请输入要增加的用户的姓名:");
String username=in.next();
pstm.setString(1,username);
System.out.println("请输入要增加的用户的密码:");
String password=in.next();
pstm.setString(2,password);
System.out.println("请输入要增加的用户的tid:");
int tid=in.nextInt();
pstm.setInt(3,tid);
//产生结果集
pstm.executeUpdate();
//处理结果
//关闭连接
pstm.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
模糊查询
public static void MoHuFind(){
try {
//创建驱动
Class.forName("com.mysql.jdbc.Driver");
//连接数据库
Connection conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/lx?useSSL=true&characterEncoding=utf8", "root", "123456");
//sql语句
System.out.println("请输入关键字:");
String word=in.next();
String sql="select * from user where username like '%"+word+"%' ";
//执行sql语句
PreparedStatement pstm = conn.prepareStatement(sql);
//产生结果集
ResultSet rs = pstm.executeQuery();
//处理结果集
while (rs.next()){
System.out.println("用户编号:"+rs.getInt(1)+",用户名称:"+rs.getString(2)+
",用户密码"+rs.getString(3)+",用户类型"+rs.getInt(4));
}
//关闭连接
rs.close();
pstm.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
模糊查询的sql语句
System.out.println("请输入关键字:");
String word=in.next();
String sql="select * from user where username like '%"+word+"%' ";
//用like来实现模糊查询,'%"+word+"%'