VB.NET数据库增删改查
时间: 2023-09-09 11:09:55 浏览: 221
以下是 VB.NET 中对数据库进行增删改查的示例代码:
1. 连接数据库
```
Dim conn As New SqlConnection("Data Source=服务器名;Initial Catalog=数据库名;User ID=用户名;Password=密码")
conn.Open()
```
2. 插入数据
```
Dim sql As String = "INSERT INTO 表名 (列1, 列2, 列3) VALUES (@列1, @列2, @列3)"
Dim cmd As New SqlCommand(sql, conn)
cmd.Parameters.AddWithValue("@列1", 值1)
cmd.Parameters.AddWithValue("@列2", 值2)
cmd.Parameters.AddWithValue("@列3", 值3)
cmd.ExecuteNonQuery()
```
3. 更新数据
```
Dim sql As String = "UPDATE 表名 SET 列1 = @列1, 列2 = @列2 WHERE 列3 = @列3"
Dim cmd As New SqlCommand(sql, conn)
cmd.Parameters.AddWithValue("@列1", 新值1)
cmd.Parameters.AddWithValue("@列2", 新值2)
cmd.Parameters.AddWithValue("@列3", 条件值)
cmd.ExecuteNonQuery()
```
4. 删除数据
```
Dim sql As String = "DELETE FROM 表名 WHERE 列 = @列"
Dim cmd As New SqlCommand(sql, conn)
cmd.Parameters.AddWithValue("@列", 值)
cmd.ExecuteNonQuery()
```
5. 查询数据
```
Dim sql As String = "SELECT 列1, 列2 FROM 表名 WHERE 列3 = @列3"
Dim cmd As New SqlCommand(sql, conn)
cmd.Parameters.AddWithValue("@列3", 值)
Dim reader As SqlDataReader = cmd.ExecuteReader()
While reader.Read()
Dim 值1 As String = reader("列1").ToString()
Dim 值2 As String = reader("列2").ToString()
End While
reader.Close()
```
阅读全文