我搜索了我的答案,却发现某人的代码中有拼写错误。
我还没有找到为什么这段代码没有ExecuteScalar()
的定义。实际上,当我实际将行添加到SQL数据库时,我可能需要捕获Customer_Id
,因为它是自动递增的。
这是我遇到问题的代码:
if (customer_IDTextBox == null)
{
sqlConnection.Open();
string SQL = "SELECT MAX(Customer_ID) FROM Customer";
int maxId = Convert.ToInt32(SQL.ExecuteScalar());
sqlConnection.Close();
}
答案 0 :(得分:2)
您需要创建SqlCommand
的实例,然后将连接和查询分配给它。
请尝试使用此代码。 (一些建议。我已经在using
陈述中包围了你的联系和命令,所以不需要关闭任何东西......他们将被处置掉。尽量创建尽可能接近您需要的连接和命令。)
int maxId = -1;
if (customer_IDTextBox == null)
{
using (var sqlConnection = new SqlConnection(/* your connection string */))
{
sqlConnection.Open();
string query = "SELECT MAX(Customer_ID) FROM Customer";
using (var sqlCommand = new SqlCommand(query, sqlConnection))
{
maxId = Convert.ToInt32(sqlCommand.ExecuteScalar());
}
}
}