Cannot detect error in the following jdbc code
replacing it with
package p1;
import java.sql.*;
public class jdbcDemo
{
public static void main(String args[])
{ int id = 0;
try
{ Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection("jdbc:odbc:loginDSN");
Connection con1 = DriverManager.getConnection("jdbc:odbc:loginDSN");
Statement stat = con.createStatement();
System.out.println("got connection");
ResultSet rs = stat.executeQuery("Select max(UID) from mytable");
while(rs.next())
{ id=rs.getInt(1);
}
id++;
System.out.println(id);
PreparedStatement ps = con1.prepareStatement("Insert into mytable(UID,Username,Password) values(?,?,?)");
ps.setInt(1,id);
ps.setString(2,"abhi");
ps.setString(3,"bindra");
ps.executeUpdate();
}
catch(Exception e)
{
e.printStackTrace();
}
开发者_Python百科
}
}
the output is
got connection 6
but the changes are no reflected :(
You are trying to INSERT a new UID with the current MAX(UID). I imagine UID is the Primary Key, thus requiring uniqueness. Either add one to id during the insert (also using WhiteFang34's suggestion), use a sequence, or some other mechanism for autoupdating the column (autonumber in MySQL for instance).
Since you're reading UID
as an int
, you might need to set it as one too. You also likely need to increase it by one since you're currently using the max(UID)
that already exists.
ps.setInt(1, id + 1);
Or perhaps you don't need to specify it at all because it's an auto-incrementing column?
精彩评论