java sql server创建表
时间: 2023-11-23 16:07:39 浏览: 95
以下是Java连接SQL Server并创建表的示例代码:
```java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class CreateTable {
public static void main(String[] args) {
String url = "jdbc:sqlserver://localhost:1433;databaseName=testdb";
String user = "username";
String password = "password";
String sql1 = "create table dept("
+ "dept_id int constraint pk_dept_id primary key,"
+ "dept_name nvarchar(20),"
+ "dept_address nvarchar(100)"
+ ")"; String sql2 = "create table emp("
+ "emp_id int constraint pk_emp_id primary key,"
+ "emp_name nvarchar(20),"
+ "emp_age int,"
+ "emp_sex nvarchar(1),"
+ "dept_id int constraint fk_dept_id_emp foreign key references dept(dept_id)"
+ ")";
try (Connection con = DriverManager.getConnection(url, user, password);
Statement stmt = con.createStatement()) {
stmt.executeUpdate(sql1);
stmt.executeUpdate(sql2);
System.out.println("Tables created successfully.");
} catch (SQLException e) {
e.printStackTrace();
}
}
}
```
这个示例代码使用JDBC连接SQL Server数据库,并创建了两个表dept和emp。其中,dept表包含dept_id、dept_name和dept_address三个字段,emp表包含emp_id、emp_name、emp_age、emp_sex和dept_id五个字段。在emp表中,dept_id字段是一个外键,参考了dept表的dept_id字段。
阅读全文