c#:向数据库MySQL中导入数据信息
1.在MySQL中创建对应的表空间,table
(1)创建表空间为cabledb
(2)在表空间下创建对应的table,例如cablebox 在表中编写对应的列 键值等等
2.连接数据库
(1)传入对应的表信息
CableInfoFile.ImportCableItemInfo(表中列信息, 表空间, 对应表名称);
(2)与MySQL创建连接
public static bool ImportCableItemInfo(表中列信息, string 表空间名称, string 表名)
{
using (MySqlConnection conn = new MySqlConnection(CableInfoFile.GetConnStr(StationName)))//创建连接
{
try
{
conn.Open();
ImportItemInfo(conn, 传入信息集合, 表空间, 表名);
}
finally
{
conn.Close();
}
}
return true;
}
(3)ImportItemInfo函数 执行连接mysql
public static bool ImportItemInfo(MySqlConnection conn, List<CableInfo> InfoList, string StationName, string TableName)
{
MySqlCommand cmd = new MySqlCommand();
cmd.Connection = conn;
MySqlTransaction tx = conn.BeginTransaction();
cmd.Transaction = tx;
cmd.CommandText = string.Format("truncate table {0}.{1}", StationName, TableName);
cmd.ExecuteNonQuery();
try
{
foreach (CableInfo Info in InfoList)
{
for (int i = 0; i < Info.CableLineNames.Count; i++)
{
string strsql = GetCableLineInfoSqlString(Info, StationName, TableName, i);//sql语句 传入对应的信息 表空间,表名,
if (strsql.Trim().Length > 1)
{
cmd.CommandText = strsql;
cmd.ExecuteNonQuery();
}
}
}
tx.Commit();
}
catch (System.Data.SqlClient.SqlException E)
{
tx.Rollback();
throw new Exception(E.Message);
}
return true;
}
(4)GetCableLineInfoSqlString函数
private static string GetCableLineInfoSqlString(CableInfo info, string StationName, string TableName, int Index)
{
string sqlStr;
sqlStr = string.Format("INSERT INTO {0}.{1} (d1, d2, d3)" +
"VALUES('{2}','{3}',{4})",
StationName, TableName, info.Name, info.CableLineNames[Index], Index + 1);
//向表中添加对应的数据信息 每行每列
return sqlStr;
}