您的位置:首页 > 数据库 > MySQL

对MySQL自增字段的操作

2008-06-04 14:48 253 查看

插入数据

首先我们建表如下:



index.jsp:
<%@page contentType="text/html;charset=gb2312" import="java.sql.*"%>
<HTML>
<HEAD>
<TITLE>JDBC连接</TITLE>
</HEAD>
<BODY>
<%
String DBDRIVER = "com.mysql.jdbc.Driver" ;
String DBURL = "jdbc:mysql://localhost:3306/test" ;
String DBUSER = "niexin" ;
String DBPASSWORD = "niexin" ;
String sql = null ;
Connection conn = null ;
Statement stmt = null ;
%>
<%
try
{
Class.forName(DBDRIVER) ;
conn = DriverManager.getConnection(DBURL,DBUSER,DBPASSWORD) ;
stmt = conn.createStatement() ;
sql = "insert into inctable (name) values ('张三')" ;
stmt.executeUpdate(sql) ;
out.println("数据库插入成功");
stmt.close() ;
conn.close() ;
}
catch(Exception e)
{
out.println(e) ;
}
%>
</BODY>
</HTML>
我们在写SQL插入语句时,应当省略掉自增字段。

取得自增字段当前值

index.jsp:
<%@page contentType="text/html;charset=gb2312" import="java.sql.*"%>
<HTML>
<HEAD>
<TITLE>JDBC连接</TITLE>
</HEAD>
<BODY>
<%
String DBDRIVER = "com.mysql.jdbc.Driver" ;
String DBURL = "jdbc:mysql://localhost:3306/test" ;
String DBUSER = "niexin" ;
String DBPASSWORD = "niexin" ;
String sql = null ;
Connection conn = null ;
Statement stmt = null ;
ResultSet rs = null ;
%>
<%
try
{
Class.forName(DBDRIVER) ;
conn = DriverManager.getConnection(DBURL,DBUSER,DBPASSWORD) ;
stmt = conn.createStatement() ;
sql = "insert into inctable (name) values ('张三')" ;
stmt.executeUpdate(sql) ;
out.println("数据库插入成功");
int autoIncKey = -1;
rs = stmt.getGeneratedKeys();
if (rs.next()) {
autoIncKey = rs.getInt(1);
}
rs.close();
out.println("自增字段当前值:"+ autoIncKey);
stmt.close() ;
conn.close() ;
}
catch(Exception e)
{
out.println(e) ;
}
%>
</BODY>
</HTML>
注意:如果这里使用的是PreparedStatement对象,getGeneratedKeys()方法同样适用。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: