2014-10-17 129 views
-4

我已经搜索了我的答案,只是发现某人的代码中存在拼写错误。为什么我没有'ExecuteScalar'的定义?

我还未发现此代码无定义为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(); 
} 
+2

看到这是一个字符串扩展方法会很有趣。 – 2014-10-17 04:18:58

回答

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()); 
     } 
    } 
} 
相关问题