Java 代码创建MySQL表 并设置主键自增怎么实现
时间: 2024-03-12 15:48:50 浏览: 144
ID自增JAVA类方法
5星 · 资源好评率100%
可以使用以下的Java代码来创建MySQL表,并设置主键自增:
```java
import java.sql.*;
public class Main {
static final String DB_URL = "jdbc:mysql://localhost:3306/mydatabase";
static final String USER = "username";
static final String PASS = "password";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try{
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL,USER,PASS);
System.out.println("Creating table...");
stmt = conn.createStatement();
String sql = "CREATE TABLE Persons " +
"(id INT NOT NULL AUTO_INCREMENT, " +
" first_name VARCHAR(255), " +
" last_name VARCHAR(255), " +
" age INT, " +
" PRIMARY KEY ( id ))";
stmt.executeUpdate(sql);
System.out.println("Table created successfully...");
}catch(SQLException se){
se.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}finally{
try{
if(stmt!=null)
conn.close();
}catch(SQLException se){
}
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}
}
System.out.println("Goodbye!");
}
}
```
在上面的代码中,我们使用了`AUTO_INCREMENT`关键字来设置主键自增。
阅读全文