mysql> CREATE table AutoIncrement -> ( -> IdAuto int autoincrement, -> primary key (IdAuto) -> ) Query OK, 0 rows affected (0. Firstly, we will create a table with the help of INSERT command. In our case as we have only one auto generated value (for student_id column) we get only single record in this result set. To know the current autoincrement value, we can use the lastinsertid () function. It gives us the result set of all auto generated key values.
The getGeneratedKeys() method is key here. Finally we have last inserted value in studentId variable. The above code is filled with comments and is pretty self explanatory. execute the insert statement, if success get the primary key value if (ps.executeUpdate() > 0) Code language: JavaScript ( javascript )
local variable to hold auto generated student id .PRICE - 101 Table 500 102 Chair 200 103 TableLamp 300 104 Glass 250 JDBC program for auto increment as primary key in MySQL database. I am already aware of the getGeneratedKeys() method in JDBC to do this following an insert, but my application requires the ID before insertion. TL DR: I want to be able to get the AUTOINCREMENT id of a table before an INSERT statement. It uses parent/child tables linked with foreign keys. PreparedStatement ps = connection.prepareStatement(QUERY, Im developing a MySQL database project using JDBC. prepare statement to execute insert query // note the 2nd argument passed to prepareStatement() method // pass name of primary key column, in this case student_id is // generated from sequence
get database connection from connection stringĬonnection connection = "scott", "tiger") Well organized and easy to understand Web building tutorials with lots of examples of how to use HTML, CSS, JavaScript, SQL, Python, PHP, Bootstrap, Java, XML and more.