package test;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Scanner;
public class test{
public static void main(String[] args)throws Exception {
// 加载数据库驱动,注册到驱动管理器
Class.forName("com.mysql.jdbc.Driver");
// 数据库连接字符串
String url = "jdbc:mysql://localhost:3306/test";
// 数据库用户名
String username = "root";
// 数据库密码
String password = "2443243838";
// 创建Connection连接
Connection conn = DriverManager.getConnection(url,username,password);
// 判断 数据库连接是否为空
Statement st=conn.createStatement();
Scanner scanner = new Scanner(System.in);
System.out.println("1,数据注册\t");
System.out.println("2,登录\t");
System.out.println("请输入你要做的操作:\t");
int n= scanner.nextInt();
if(n==1){
// 输出连接信息
System.out.println("请输入用户名字:");
String username1 = scanner.next();
System.out.println("请输入密码:");
String password1 = scanner.next();
String sql="select * from user where username='"+username1+"'";
ResultSet ra= st.executeQuery(sql);
if(ra.next()){
System.out.println("用户已存在");
}else{
sql="insert into user values=('"+username1+"','"+password1+"')";
int i=st.executeUpdate(sql);
if(i!=0){
System.out.println("添加成功");
}else{
System.out.println("添加失败");
}
}
// 关闭数据库连接
}else if(n==2){
}else{
// 输出连接信息
System.out.println("数据库连接失败!");
}
}
}
1,数据注册
2,登录
请输入你要做的操作:
1
请输入用户名字:
刘备
请输入密码:
123456
Exception in thread "main" com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '=('刘备','123456')' at line 1
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
at com.mysql.jdbc.Util.getInstance(Util.java:386)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1053)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4096)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4028)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2490)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2651)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2728)
at com.mysql.jdbc.StatementImpl.executeUpdate(StatementImpl.java:1811)
at com.mysql.jdbc.StatementImpl.executeUpdate(StatementImpl.java:1725)
at test.test.main(test.java:43)