JavaJDBC - 注册功能(executeUpdate())

代码实现

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("用户名已存在");
    }
    }
}


运行结果:注册成功与用户已存在

注册成功

用户已存在

数据库数据

数据信息

猜你喜欢

转载自blog.csdn.net/zhu_fangyuan/article/details/108380901