我创建了插入新记录的函数 - 我直接向它提交查询。 我的问题是最佳吗?这是否可靠,并保证正常运行?如果不;请指教。从C#到MySQL执行INSERT语句的正确方法
static String Server = "";
static String Username = "";
static String Name = "";
static String password = "";
static String conString = "SERVER=" + Server + ";DATABASE=" + Name + ";UID=" + Username + ";PASSWORD=" + password + ";connect timeout=500000;Compress=true;";
public bool InsertSQL(String Query)
{
int tmp = 0;
try
{
using (MySqlConnection mycon = new MySqlConnection(conString))
{
using (MySqlCommand cmd = new MySqlCommand(Query, mycon))
{
mycon.Open();
try
{
tmp = cmd.ExecuteNonQuery();
}
catch
{
if (mycon.State == ConnectionState.Open)
{
mycon.Close();
}
}
mycon.Close();
}
}
}
catch { return tmp > 0 == true ? true : false; }
return tmp > 0 == true ? true : false;
}
这是我在其他函数中创建的SQL插入并传递为文本插入函数。我接受所有建议!
String insertSql = @"INSERT INTO `gps_unit_location`
(`idgps_unit`,`lat`,`long`,`ip`,`unique_id`,
`loc_age`,`reason_code`,`speed_kmh`,
`VehHdg`,`Odometer`,`event_time_gmt_unix`,`switches`, `engine_on_off`, `dt`)
VALUES
(
(Select idgps_unit from gps_unit where serial=" + serial + "),'" + lat + "','" + lon + "','" + IP + "','" + unique_id + @"',
'" + LocAge_mins + "','" + ReasonCode + "','" + Speed + @"',
'" + VehHdg + "','" + Odometer + "','" + EventTime_GMTUnix + "','" + Switches + "', '" + engine_on_off + @"', DATE_ADD(NOW(), INTERVAL 1 HOUR))
";
你在哪里设置查询对象? – Brian 2013-03-07 17:01:58
它被设置在其他功能中并作为文本传递 – Andrew 2013-03-07 17:02:56