我创建了这个插入新记录的函数——我直接向它提交查询。我的问题 - 它是最优的吗?它是万无一失的并保证正常运行吗?如果不; 请指教。
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))
";