.net framework 插入sqlserver 2000 之后返回行ID
时间: 2023-08-10 19:09:46 浏览: 55
您好,应该可以使用以下代码将数据插入到 SQL Server 2000 中,并返回插入的行ID:
```csharp
using System.Data.SqlClient;
// 设置连接字符串
string connectionString = "Data Source=myServerAddress;Initial Catalog=myDataBase;User Id=myUsername;Password=myPassword;";
// 设置插入 SQL 语句
string insertSql = "INSERT INTO myTable (column1, column2) VALUES (@value1, @value2); SELECT SCOPE_IDENTITY();";
// 建立数据库连接
using (SqlConnection connection = new SqlConnection(connectionString))
{
// 建立 SQL 命令对象
using (SqlCommand command = new SqlCommand(insertSql, connection))
{
// 设置参数
command.Parameters.AddWithValue("@value1", value1);
command.Parameters.AddWithValue("@value2", value2);
// 打开数据库连接
connection.Open();
// 执行 SQL 语句并返回插入的行ID
int insertedRowId = Convert.ToInt32(command.ExecuteScalar());
// 关闭数据库连接
connection.Close();
// 返回插入的行ID
return insertedRowId;
}
}
```
其中,`SCOPE_IDENTITY()` 函数可以返回插入的行ID。请将代码中的 `myServerAddress`、`myDataBase`、`myUsername`、`myPassword`、`myTable`、`column1` 和 `column2` 替换为实际的值,`value1` 和 `value2` 替换为要插入的数据。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)