查询执行没有任何反应

时间:2015-03-05 00:54:00

标签: c# sql-server

我有这个简单的代码C#和SQL Server数据库:

int refcodenum = getOrderNum();
string refcode = "E" + refcodenum;
byte[] personalpic = getBarcode(refcodenum);

SqlCommand cm2 = new SqlCommand();
cm2.Connection = cn;
cm2.CommandText = "Update Clients set ReferenceNumber='" + refcode + "',ReferenceBarcode=@photo where NetNumber='"+id+"'";

cm2.Parameters.Add("@photo", SqlDbType.Image, personalpic.Length).Value = personalpic;

// here like cursor stop
cm2.ExecuteNonQuery();

lastpage = "x";

File.Delete(Directory.GetCurrentDirectory() + @"\myimage.jpg");

我已经运行了但查询执行没有任何反应我使用MessageBox来识别出问题的行

int refcodenum = getOrderNum();
string refcode = "E" + refcodenum;
byte[] personalpic = getBarcode(refcodenum);

SqlCommand cm2 = new SqlCommand();
cm2.Connection = cn;

MessageBox.Show("1");

cm2.CommandText = "Update Clients set ReferenceNumber='" + refcode + "',ReferenceBarcode=@photo where NetNumber='"+id+"'";

MessageBox.Show("2");

cm2.Parameters.Add("@photo", SqlDbType.Image, personalpic.Length).Value = personalpic;
MessageBox.Show("3");

// here cursor stops
cm2.ExecuteNonQuery();

// that messagebox isn't shown
MessageBox.Show("4");

lastpage = "x";
File.Delete(Directory.GetCurrentDirectory() + @"\myimage.jpg");

任何帮助将不胜感激

1 个答案:

答案 0 :(得分:0)

您尚未打开连接。见下文。

您还应该使用using语法来使用IDisposable

int refcodenum = getOrderNum();
string refcode = "E" + refcodenum;
byte[] personalpic = getBarcode(refcodenum);
var sqlCmdText = "Update Clients set ReferenceNumber='" + refcode + "',ReferenceBarcode=@photo where NetNumber='"+id+"'";

try
{
    using (var sqlConnection = new SqlConnection([YOUR CONNECTION STRING HERE]))
    {
        using (var sqlCommand = new SqlCommand(sqlCmdText, sqlConnection))
        {
            sqlCommand.CommandType = CommandType.Text;

            sqlCommand.Parameters.Add("@photo", SqlDbType.Image, personalpic.Length).Value = personalpic;
            sqlConnection.Open();

            sqlCommand.ExecuteNonQuery();

        }
    }
}
catch (Exception ex)
{
    throw new DataException(ex.Message);
}