代码实现
package com.fy.jdbc;
import com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.util.Scanner;
public class TestRegister {
public static void main(String[] args) throws Exception {
System.out.println("请输入用户名:");
String user = new Scanner(System.in).nextLine();
System.out.println("请输入密码:");
String pwd = new Scanner(System.in).nextLine();
register(user,pwd);
}
private static void register(String user,String pwd) throws Exception {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/day0901", "root", "1234");
String sql = "insert into tb3 values ('"+user+"','"+pwd+"')";
Statement stmt = conn.createStatement();
int row = stmt.executeUpdate(sql);
if(row != 0){
System.out.println("注册成功");
}else{
System.out.println("注册失败");
}
} catch (MySQLIntegrityConstraintViolationException e) {
System.out.println("用户名已存在");
}
}
}
运行结果:注册成功与用户已存在
数据库数据