(1)
import java.sql.*;
public class jdbcDemo
{static Connection con=null;
public static void main(String args[])
{ int id = 0;
try
{ Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection("jdbc:odbc:login");
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 = con.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();
}
}
}
(2)
import java.sql.*;
public class jdbcDemo
{static Connection con=null;
public static void main(String args[])
{ int id = 0;
try
{ Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection("jdbc:odbc:login");
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 = con.prepareStatement("INSERT into mytable(UID,Username,Password) values(?,?,?)");
ps.setInt(1,id);
ps.setString(2,"abhi");
ps.setString(3,"bindra");
ps.executeUpdate();
String s1,s2;
ResultSet rs1 = stat.executeQuery("Select * from mytable where UID="+id+"");
while(rs1.next())
{
s1=rs1.getString(2);
s2=rs1.getString(3);
System.out.print(s1+s2);
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
部分
ResultSet rs1 = stat.executeQuery("Select * from mytable where UID="+id+"");
while(rs1.next())
{
s1=rs1.getString(2);
s2=rs1.getString(3);
System.out.print(s1+s2);
}
为什么这部分必不可少?为什么不执行ps.executeUpdate()将行插入表中。如果没有将部分插入(1)中,则记录不会出现在表中。
答案 0 :(得分:1)
你有没有关闭你的陈述,结果集和联系?它们应该是最终条款。
答案 1 :(得分:0)
在检索结果集之前,即使在INSERT,UPDATE或DELETE语句中也不会发生自动提交。请参阅:http://download.oracle.com/javase/tutorial/jdbc/basics/transactions.html
默认情况下,SQL语句在完成时提交,而不是在执行时提交。检索到所有结果集和更新计数后,语句即完成。
如果您对更新结果不感兴趣,请在执行后立即通过con.commit()
向数据库发送提交。