jil*_*ill 3 c# sql t-sql sql-server ado.net
我是一个新手,想要一些关于C#编程的建议
我想将文本框中的值存储到数据库中.到目前为止,我有以下内容:
string connectionString = @"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Customers.mdf;Integrated Security=True;User Instance=True";
SqlConnection connection = new SqlConnection(connectionString);
connection.Open();
string query = "INSERT INTO ProjectList (ProjectName, BiddingDueDate, Status, ProjectStartDate, ProjectEndDate, AssignedTo, PointsWorth, StaffCredits) VALUES ('"+projName+"', '"+bidDueDate+"', '"+status+"', '"+projectStartDate+"', '"+projectEndDate+"', '"+assignedTo+"', '"+pointsWorth+"', '"+aStaffCredits+"')";
SqlCommand command = new SqlCommand(query, connection);
command.ExecuteNonQuery();
connection.Close();
Run Code Online (Sandbox Code Playgroud)
代码中没有错误,但我似乎无法弄清楚为什么数据库中没有存储任何内容.
至少你的代码应如下所示:
void SaveData(string projectName, DateTime biddingDueDate, string status, DateTime projectStartDate, string assignedTo, int pointsWorth, string staffCredits)
{
try
{
string connectionString = @"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Customers.mdf;Integrated Security=True;User Instance=True";
using (SqlConnection connection = new SqlConnection(connectionString))
using (SqlCommand command = connection.CreateCommand())
{
command.CommandText = "INSERT INTO ProjectList (ProjectName, BiddingDueDate, Status, ProjectStartDate, ProjectEndDate, AssignedTo, PointsWorth, StaffCredits) VALUES (@projectName, @biddingDueDate, @status, @projectStartDate, @projectStartDate, @assignedTo, @pointsWorth, @staffCredits)";
command.Parameters.AddWithValue("@projectName", projectName);
command.Parameters.AddWithValue("@biddingDueDate", biddingDueDate);
command.Parameters.AddWithValue("@status", status);
command.Parameters.AddWithValue("@projectStartDate", projectStartDate);
command.Parameters.AddWithValue("@assignedTo", assignedTo);
command.Parameters.AddWithValue("@pointsWorth", pointsWorth);
command.Parameters.AddWithValue("@staffCredits", staffCredits);
connection.Open();
command.ExecuteNonQuery();
}
}
catch (SqlException ex)
{
Console.WriteLine(ex.Message);
}
}
Run Code Online (Sandbox Code Playgroud)
参数的类型可以自动确定(尝试):
command.Parameters.AddWithValue("@biddingDueDate", biddingDueDate);
Run Code Online (Sandbox Code Playgroud)
或手动指定:
command.Parameters.Add("@biddingDueDate", System.Data.SqlDbType.DateTime).Value = biddingDueDate;
Run Code Online (Sandbox Code Playgroud)
您还可以将日期转换为具有指定格式的字符串,以最大限度地降低数据库端错误解析(因为文化依赖的特殊性等)的风险:
command.Parameters.Add("@biddingDueDate", System.Data.SqlDbType.DateTime).Value = biddingDueDate.ToString("yyyy-MM-dd"); // also you can use just yyyyMMdd
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
48516 次 |
最近记录: |