我得到了这个运行时异常
SQLException未处理
,细节是
不允许从数据类型varchar到二进制的隐式转换。使用CONVERT函数运行此查询。
错误在行
cmd.ExecuteNonQuery();
代码:
SqlConnection con = new SqlConnection("Data Source=localhost\\SQLEXPRESS;Initial Catalog=sample;Integrated Security=True;");
con.Open();
SqlCommand cmd = new SqlCommand("INSERT INTO patientinfo (patientname, patientid, gender, dob , contactaddress, contactno, doa , referreddoctor, diagnosis, medication, ward) VALUES ('" + patientname + "','" + patientid + "','" + gender + "','" + dtpdob.Value.ToString("dd/MM/yyyy") + "','" + contactaddress + "','" + contactno + "','" + dtpdoa.Value.ToString("dd/MM/yyyy") + "','" + referreddoctor + "','" + diagnosis + "','" + medication + "','" + wardno + "')",con);
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Details Saved ! ", "PatientInformationSystem", MessageBoxButtons.OK, MessageBoxIcon.Information);
clearall();
请帮忙
答案 0 :(得分:2)
您需要学习正确的ADO.NET编程的基础知识:
using() { ... }
块来确保妥善处理一次性物品,例如SqlConnection
和SqlCommand
所以简而言之,我会改写你的代码:
// define your parametrized query
string insertStmt = @"INSERT INTO patientinfo(patientname, patientid, gender, dob, contactaddress, contactno, doa, referreddoctor, diagnosis, medication, ward)
VALUES (@patientname, @patientid, @gender, @dob, @contactaddress, @contactno, @doa, @referreddoctor, @diagnosis, @medication, @ward);"
// define your connection string - typically, you'd read this from a config file
string connectionString = "Data Source=localhost\\SQLEXPRESS;Initial Catalog=sample;Integrated Security=True;";
// wrap connection and command in using() blocks
using (SqlConnection con = new SqlConnection(connectionString))
using (SqlCommand cmd = new SqlCommand(insertStmt, con))
{
// now add and setup the parameter list
cmd.Parameters.Add("@patientname", SqlDbType.VarChar, 100).Value = patientname;
cmd.Parameters.Add("@patientid", SqlDbType.Int).Value = patientid;
..... and so forth, until *ALL* parameters have been added and defined
// open connection, execute command, close connection
con.Open();
int rowsAffected = cmd.ExecuteNonQuery();
con.Close();
}
执行此操作时,应该非常清楚哪个参数的类型为binary
,并且在将其分配给参数值之前,应该首先明确哪个字符串需要转换为binary
。