如何使用java添加自动增量值?
我在Mysql中使用如何使用java添加自动增量值?,java,mysql,sql,database,prepared-statement,Java,Mysql,Sql,Database,Prepared Statement,我在Mysql中使用 Create table ( id int auto_increment, us varchar(100), ps varchar(1000) ); 并使用java通过我的GUI应用程序添加值: 我使用以下方法将值添加到数据库中: public static void Mysql(String u, String p) throws NoSuchAlgorithmException, InvalidKeySpecException { S
Create table
(
id int auto_increment,
us varchar(100),
ps varchar(1000)
);
并使用java通过我的GUI应用程序添加值:
我使用以下方法将值添加到数据库中:
public static void Mysql(String u, String p) throws NoSuchAlgorithmException, InvalidKeySpecException
{
String hashpass=passhash(p);//throws declaration for this statement
try{
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/bs","root","root");
String query = " insert into login (id,us,ps)"
+ " values (?,?, ?)";
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery("select * from login");
int id=0;
while(rs.next())
{
id= rs.getInt(1);
}
PreparedStatement preparedStmt = con.prepareStatement(query);
preparedStmt.setInt(1, id++); //I don't want this method because id is auto increment
preparedStmt.setString(2,u);
preparedStmt.setString(3,hashpass);
preparedStmt.execute();
con.close();
}catch(Exception e){ System.out.println(e);}
}
一切正常
但是id是自动递增的,我不需要在添加其他列值时向id添加值
我不能像那样添加,而通过java添加,比如只添加us、ps列,id将自动递增
是否有任何方法可以在不传递参数的情况下添加数据
从sql语句中删除列id:
String query = "insert into login (us, ps) values (?, ?)";
并且不要在准备好的语句中为其设置任何值,因此请删除此行:
preparedStmt.setInt(1, id++);
列id是自动输入的,因此其值将由MySql设置。
当然,将其他行的索引更改为1和2:
preparedStmt.setString(1,u);
preparedStmt.setString(2,hashpass);
从sql语句中删除列id:
String query = "insert into login (us, ps) values (?, ?)";
并且不要在准备好的语句中为其设置任何值,因此请删除此行:
preparedStmt.setInt(1, id++);
列id是自动输入的,因此其值将由MySql设置。
当然,将其他行的索引更改为1和2:
preparedStmt.setString(1,u);
preparedStmt.setString(2,hashpass);
您可以插入没有ID的数据,因为它将从SQL自动生成 public static void MysqlString u,String p抛出NoSuchAlgorithmException,InvalidKeySpecException{ 字符串hashpass=passhashp; 试试{ Class.forNamecom.mysql.cj.jdbc.Driver; Connection con=DriverManager.getConnectionjdbc:mysql://127.0.0.1:3306/bs,根,根; String query=插入登录us,ps值?,?;//检查此处 语句stmt=con.createStatement; ResultSet rs=stmt.executeQueryselect*from login; PreparedStatement preparedStmt=con.prepareStatementquery; 准备好的固定管柱1,u; 准备好的stmt.setString2,hashpass; preparedStmt.execute; con.close; }卡奇{ System.out.printlne;} } }
您可以插入没有ID的数据,因为它将从SQL自动生成 public static void MysqlString u,String p抛出NoSuchAlgorithmException,InvalidKeySpecException{ 字符串hashpass=passhashp; 试试{ Class.forNamecom.mysql.cj.jdbc.Driver; Connection con=DriverManager.getConnectionjdbc:mysql://127.0.0.1:3306/bs,根,根; String query=插入登录us,ps值?,?;//检查此处 语句stmt=con.createStatement; ResultSet rs=stmt.executeQueryselect*from login; PreparedStatement preparedStmt=con.prepareStatementquery; 准备好的固定管柱1,u; 准备好的stmt.setString2,hashpass; preparedStmt.execute; con.close; }卡奇{ System.out.printlne;} } }
谢谢,所以muchI错过了要更改的索引值谢谢,所以muchI错过了要更改的索引值