我试图使Qr码应用程序(生成,然后保存在数据库),但有一些错误与我的程序代码
本文关键字:错误 代码 程序 我的 数据库 保存 Qr 应用程序 然后 生成 存在 | 更新日期: 2023-09-27 18:14:38
我得到这两个错误
'SqlConnection'没有包含'Parameters'的定义,也没有扩展名可以找到接受类型为"SqlConnection"的第一个参数的方法"Parameters"(您是否缺少using指令或程序集引用?)
和
源错误:'SqlConnection'不包含'ExecuteNonQuery'的定义,并且无法找到接受'SqlConnection'类型的第一个参数的扩展方法'ExecuteNonQuery'(您是否缺少using指令或程序集引用?)
SqlConnection con1;
con1 = new SqlConnection(@"Data Source=(LocalDB)'MSSQLLocalDB;AttachDbFilename=C:'Users'User1'Documents'ESDB.mdf;Integrated Security=True;Connect Timeout=30");
con1.Open();
string qry = "Insert into QRCODES(Image) VALUES(@PIC)";
SqlConnection cmd = new SqlConnection(qry);
MemoryStream STREAM = new MemoryStream();
pictureBox1.Image.Save(STREAM,System.Drawing.Imaging.ImageFormat.Jpeg);
byte[] pic = STREAM.ToArray();
cmd.Parameters.AddWithValue("@PIC", pic);
cmd.ExecuteNonQuery();
cmd.Dispose();
con1.Close();
现在当我用
重新构建代码时SqlCommand cmd = new SqlCommand
我得到新的错误(警告),它说:
类型为"System"的未处理异常。在WindowsFormsApplication1.exe中发生NullReferenceException附加信息:对象引用未设置为对象的实例。
正在使用两个SqlConnection对象。应该是SqlCommand:
SqlConnection con1;
con1 = new SqlConnection(@"Data Source=(LocalDB)'MSSQLLocalDB;AttachDbFilename=C:'Users'User1'Documents'ESDB.mdf;Integrated Security=True;Connect Timeout=30");
con1.Open();
string qry = "Insert into QRCODES(Image) VALUES(@PIC)";
SqlCommand cmd = new SqlCommand(qry);
^^^^^^^^^^ ^^^^^^^^^^
MemoryStream STREAM = new MemoryStream();
pictureBox1.Image.Save(STREAM, System.Drawing.Imaging.ImageFormat.Jpeg);
byte[] pic = STREAM.ToArray();
cmd.Parameters.AddWithValue("@PIC", pic);
cmd.ExecuteNonQuery();
cmd.Dispose();
con1.Close();
也要小心这段代码,因为您使用的是命令和连接,而不是处理它们。它可能导致内存泄漏和一些问题。
也许你应该这样考虑重构:
using (SqlConnection con1 = new SqlConnection(@"Data Source=(LocalDB)'MSSQLLocalDB;AttachDbFilename=C:'Users'User1'Documents'ESDB.mdf;Integrated Security=True;Connect Timeout=30"))
{
con1.Open();
string qry = "Insert into QRCODES(Image) VALUES(@PIC)";
using (SqlCommand cmd = new SqlCommand(qry))
{
using (MemoryStream STREAM = new MemoryStream())
{
pictureBox1.Image.Save(STREAM, System.Drawing.Imaging.ImageFormat.Jpeg);
byte[] pic = STREAM.ToArray();
cmd.Parameters.AddWithValue("@PIC", pic);
cmd.ExecuteNonQuery();
con1.Close();
}
}
}
更新:
您的问题,正如错误所说,是命令和连接没有关联。这应该可以工作:
using (SqlConnection con1 = new SqlConnection(@"Data Source=(LocalDB)'MSSQLLocalDB;AttachDbFilename=C:'Users'User1'Documents'ESDB.mdf;Integrated Security=True;Connect Timeout=30"))
{
con1.Open();
string qry = "Insert into QRCODES(Image) VALUES(@PIC)";
using (SqlCommand cmd = con1.CreateCommand()) //associate the connection to the command
{
cmd.CommandText = qry; //assign the command text to the command.
using (var STREAM = new MemoryStream())
{
pictureBox1.Image.Save(STREAM, System.Drawing.Imaging.ImageFormat.Jpeg);
byte[] pic = STREAM.ToArray();
cmd.Parameters.AddWithValue("@PIC", pic);
cmd.ExecuteNonQuery();
con1.Close();
}
}
}