JDBC浅应用
DriverManager: 此类管理数据库驱动程序列表。使用通信协议将来自java应用程序的连接请求与适 当的数据库驱动程序匹配。 Driver:此接口处理与数据库服务器的通信,我们很少会直接与Driver对象进行交互。而是使用 DriverManager对象来管理这种类型的对象。 Connection:该接口具有用于连接数据库的所有方法。连接对象表示通信上下文,数据库的所有通信 仅通过连接对象。 Statement:使用从此接口创建的对象将SQL语句提交到数据库。用于对数据库进行通用访问。在运行时使用静态SQL语句时很有用。Statement接口不能接受参数。 PreparedStatement 多次使用SQL语句时使用。PreparedStatement接口在运行时接 受输入参数。 ResultSet:在使用Statement对象执行SQL查询后,这些对象保存从数据库检索的数据。它作为一个迭 代器,允许我们移动其数据。 SQLException:此类处理数据库应用程序中发生的任何异常。
使用jdbc,注册用户信息;并且打印成功还是失败到控制台:
刚开始的user_info表

public static void main(String[] args) {
// 注册用户 往外面uesr-info表里面插入一条记录
System.out.println("请输入用户名");
Scanner scan = new Scanner(System.in);
String name = scan.next();
System.out.println("请输入密码");
String pass = scan.next();
StringBuilder ss = new StringBuilder();
ss.append("insert into user_info(uname,upass)values(‘").append(name).append(" ‘, ").append(pass).append(" )");
System.out.println(ss.toString());
// 注册
try {
Class.forName("com.mysql.jdbc.Driver");
Connection connection = DriverManager.getConnection(url, user, password);
Statement statement = connection.createStatement();
int result = statement.executeUpdate(ss.toString());
if (result > 0) {
System.out.println("注册成功");
} else {
System.out.println("注册失败");
}
statement.close();
connection.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}结果:


使用jdbc根据用户id修改用户名称:
public static void main(String[] args) {
// 根据用户id修改用户名称
System.out.println("请输入你要修改的用户id");
Scanner scan = new Scanner(System.in);
String id = scan.next();
System.out.println("请输入你要修改的用户名");
String name = scan.next();
// ? 占位符
String sql = "update user_info set uname=? where uid=?";
// 预处理SQL语句,这个操作数据库的对象,比较智能
// 会根据我们的参数,自己来给SQL进行预处理
try {
Class.forName("com.mysql.jdbc.Driver");
Connection connection = DriverManager.getConnection(url, user, password);
// 获取一个操作数据库的对象;获取一个预处理的对象
// statement 只能执行静态的sql
// PreparedStatement 自己放参数,自己调用
PreparedStatement ps = connection.prepareStatement(sql);
// 给SQL语句里面的占位符进行赋值
ps.setString(1, name);// 给SQL第一个问号赋值
ps.setInt(2, Integer.parseInt(id));// 给第二个赋值
// 执行SQL
int ex = ps.executeUpdate();// 不要加SQL
if (ex > 0) {
System.out.println("修改成功");
} else {
System.out.println("修改失败");
}
ps.close();
connection.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}结果:

