IDEA通过代码函数对SqlServer数据库中的表进行增删查改操作
时间: 2024-03-16 13:43:42 浏览: 135
首先,在IDEA中需要引入SqlServer的JDBC驱动,可以在pom.xml文件中添加如下依赖:
```xml
<dependency>
<groupId>com.microsoft.sqlserver</groupId>
<artifactId>mssql-jdbc</artifactId>
<version>8.4.1.jre11</version>
</dependency>
```
然后,可以使用Java中的JDBC API对SqlServer进行增删查改操作。下面是一个简单的示例代码:
```java
import java.sql.*;
public class SqlServerDemo {
public static void main(String[] args) {
Connection conn = null;
try {
// 连接SqlServer数据库
conn = DriverManager.getConnection("jdbc:sqlserver://localhost:1433;DatabaseName=test", "username", "password");
// 插入数据
String sql = "INSERT INTO student (id, name, age) VALUES (?, ?, ?)";
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, 1);
pstmt.setString(2, "Tom");
pstmt.setInt(3, 18);
pstmt.executeUpdate();
// 查询数据
sql = "SELECT * FROM student WHERE id = ?";
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, 1);
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
System.out.println(rs.getInt("id") + "\t" + rs.getString("name") + "\t" + rs.getInt("age"));
}
// 更新数据
sql = "UPDATE student SET age = ? WHERE id = ?";
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, 20);
pstmt.setInt(2, 1);
pstmt.executeUpdate();
// 删除数据
sql = "DELETE FROM student WHERE id = ?";
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, 1);
pstmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}
```
其中,`jdbc:sqlserver://localhost:1433;DatabaseName=test`表示连接本地SqlServer数据库中的test数据库,需要将username和password替换为实际的用户名和密码。代码中演示了如何插入、查询、更新和删除数据。
阅读全文