增添功能
实现在控制台中通过输入的值来插入到数据库中增加对JDBC认识
如下代码:
public class JDBCDemo2 {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection connection =DriverManager.getConnection(
"jdbc:mysql://localhost:3306/birddb?characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai&rewriteBatchedStatements=true",
"root",
"root"
);
System.out.println("数据库连接成功!");
Statement statement=connection.createStatement();
System.out.println("欢迎注册");
Scanner scan = new Scanner(System.in);
System.out.println("请输入用户名");
String username=scan.nextLine();
System.out.println("请输入密码");
String password=scan.nextLine();
System.out.println("请输入昵称");
String nickname=scan.nextLine();
System.out.println("请输入年龄");
int age=scan.nextInt();
String sql="INSERT INTO userinfo1(username,password,nickname,age) " +
"VALUES('"+username+"','"+password+"','"+nickname+"','"+age+"')";
int num=statement.executeUpdate(sql);
if (num>0){
System.out.println("插入成功");
}
connection.close();
}
}
方法:
statement方法:
int executeUpdate(String sql)
用来执行DML的语句,该方法的返回值表示执行后影响了表中多少条记录
注:大于零便表示影响到了表,可判断插入成功