我正在开发VS2010 c#中的应用程序,以从SQLServer获取单行数据并将其插入MySQL。
我已经获取数据并存储在特定的字符串变量中。获取代码如下。
SqlCommand cmd = new SqlCommand("SELECT TOP (1) s_name, s_city, s_address, s_added_date, s_added_by FROM tblAQI ORDER BY s_added_date DESC", SSCon);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
s_name = (dr["s_name"].ToString());
s_city = (dr["s_city"].ToString());
s_address = (dr["s_address"].ToString());
s_added_date = (dr["s_added_date"].ToString());
s_added_by = (dr["s_added_by"].ToString());
}
所有商店都以字符串格式值。问题在于s_added_date这个变量包含日期时间值,即像11/15/2013 12:01:00 AM因为AM而无法插入MySQL。
我的插入代码如下。
mcmd.CommandText = "INSERT INTO tblaqi(s_name,s_city,s_address,s_added_date,s_added_by) VALUES(@s_name,@s_city,@s_address,s_added_date,s_added_by)";
mcmd.Parameters.AddWithValue("@s_name", s_name);
mcmd.Parameters.AddWithValue("@s_city", s_city);
mcmd.Parameters.AddWithValue("@s_address", s_address);
mcmd.Parameters.AddWithValue("@s_added_by", s_added_by);
mcmd.Parameters.AddWithValue("@s_added_date", s_added_date);
int count = mcmd.ExecuteNonQuery();
if (count != 0)
{
MessageBox.Show("Success..!!");
}
else
MessageBox.Show("Need to work");
我的问题是这将是什么问题。
提前致谢。
答案 0 :(得分:1)
解决方案1:您的查询无效:您在@
语句中缺少insert into
参数符号,如下所示
mcmd.CommandText = "INSERT INTO tblaqi(s_name,s_city,s_address,s_added_date,s_added_by) VALUES(@s_name,@s_city,@s_address,s_added_date,s_added_by)";
^^^ ^^^
应该是这个:
mcmd.CommandText = "INSERT INTO tblaqi(s_name,s_city,s_address,s_added_date,s_added_by) VALUES(@s_name,@s_city,@s_address,@s_added_date,@s_added_by)";
解决方案2:
s_added_date=s_added_date.Substring(0, s_added_date.Length - 3);//stores only 11/15/2013 12:01:00
答案 1 :(得分:1)
您应该首先存储正确的类型,因此datetime
代替varchar
。
否则,您始终必须将其解析为DateTime
,存在格式无效,本地化问题和性能不佳的风险。您可以使用DateTime.ParseExact
:
string s_added_date = dr.GetString("s_added_date");
DateTime dtAdded = DateTime.ParseExact(s_added_date , "MM/dd/yyyy hh:mm:ss tt", CultureInfo.InvariantCulture);
mcmd.Parameters.AddWithValue("@s_added_date", dtAdded);