实现功能如下:
①0选中注册,若用户名相同则注册失败,重新选择
②若用户名不存在则保存到数据库
③1选中登录,若用户名和密码符合时,登录成功。
代码如下:
package com.lucfzy;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Scanner;
public class SqlText {
private static String userID;
private static String psw1;
public static void main(String args[]) throws ClassNotFoundException, SQLException{
System.out.println("请输入数字 :0--代表注册,1--代表登录");
Scanner input = new Scanner(System.in);
while(true){
//注册模块
if (input.nextInt()==0) {
//默认输入的是字符串,所以建议测试的时候输入字符串
while(true){
System.out.println("用户名:");
Scanner scanner = new Scanner(System.in);
//获取用户名
userID = scanner.nextLine();
System.out.println("密码:");
Scanner scanner2 = new Scanner(System.in);
//获取密码
psw1 = scanner2.nextLine();
//先检查用户名是否存在,若不存在则继续注册
String sql2 = "select * from table_name where ID ="+"'"+userID+"'";
DBHelper DBquery = new DBHelper();
ResultSet rsSet = DBquery.DB(sql2);
if (rsSet.next()) {
System.out.println("该用户名已被注册,请更换您的用户名再进行注册");
DBquery.downConn();
break;
}
else{
String sql = "insert into table_name(ID,PASSWORD) values ('fzynzs','fzynzs')";
DBHelper DBupdate = new DBHelper();
DBupdate.excuteSql(sql);
System.out.println("恭喜您注册成功");
//关闭connection的连接哦,防止泄露
DBupdate.downConn();
scanner.close();
scanner2.close();
break;
}
}
}
//登录模块
else {
//默认输入的是字符串,所以建议测试的时候输入字符串
System.out.println("用户名:");
Scanner scanner = new Scanner(System.in);
userID = scanner.nextLine();
System.out.println("密码:");
Scanner scanner2 = new Scanner(System.in);
psw1 = scanner2.nextLine();
//*代表的是所有列
String sql2 = "select * from table_name where ID ="+"'"+userID+"'"+"and password="+"'"+psw1+"'";
//每次新建一个对象,就是新建一个连接connection
DBHelper dbHelper = new DBHelper();
//在数据库中查询结果,若结果存在返回登录成功
ResultSet rsResultSet = dbHelper.DB(sql2);
if(rsResultSet.next()==true){
System.out.println("登录成功");
dbHelper.downConn();
}
else{
System.out.println("登录失败,请检查您的用户名和密码是否正确");
dbHelper.downConn();
}
scanner.close();
scanner2.close();
break;
}
}
input.close();
}
}
class DBHelper{
public Connection connection;
public PreparedStatement preparedStatement;
public DBHelper() throws SQLException, ClassNotFoundException{
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:mysql://your IP Address:3306/DBname","username","password");
}
public ResultSet DB(String sql) throws ClassNotFoundException, SQLException{
preparedStatement = connection.prepareStatement(sql);
ResultSet resultSet = preparedStatement.executeQuery();
return resultSet;
}
public void excuteSql(String sql) throws SQLException{
preparedStatement = connection.prepareStatement(sql);
preparedStatement.executeUpdate();
}
public void downConn() throws SQLException{
connection.close();
}
}
大家可以在此基础上进行优化,并添加图形化界面。完善该程序,bingo~