您的位置:首页 > 数据库 > MySQL

从sqlserver到mysql的数据导入导出

2007-08-31 16:13 519 查看
private string ImportData(string TableName)
{
//try
//{
//string mystrconn = "server=192.168.1.228;database=db_music;uid=a8user;pwd=a8user;";
//MySql.Data.MySqlClient.MySqlConnection myconn = new MySqlConnection(mystrconn);
//myconn.Open();
Application.DoEvents();

string sql = string.Format("select {1} * from {0}", TableName, this.txtTop.Text == "" ? "" : "top " + this.txtTop.Text);
DataSet ds = SqlHelper.ExecuteDataset(txtSqlConn.Text, CommandType.Text, sql);

int curPage = 0;
int countSize = ds.Tables[0].Rows.Count;
if (this.txtTop.Text != "" && countSize>int.Parse(this.txtTop.Text))
countSize = int.Parse(this.txtTop.Text);
int pagesize = countSize;
if (this.textBox2.Text != "")
pagesize = int.Parse(this.textBox2.Text);
string filepath = this.textBox1.Text + TableName + curPage.ToString() + ".txt";
FileStream fs = File.Create(filepath);
string strGenSql = "";
for (int i = 0; i < countSize; i++)
{
Application.DoEvents();
if ((i % pagesize) == 0)
{
curPage++;
filepath = this.textBox1.Text + TableName + curPage.ToString() + ".txt";
fs = File.Create(filepath);
}
string strValue = "";
for (int j = 0; j < ds.Tables[0].Columns.Count; j++)
{
strValue += GetFormatValue(ds.Tables[0].Rows[i][j].ToString(), ds.Tables[0].Columns[j].DataType.ToString()) + ",";
}
if (strValue != "") strValue = strValue.Substring(0, strValue.Length - 1);
string exsql = string.Format("insert into {0} select {1};/r/n", TableName, strValue);
//strGenSql += exsql;
Byte[] info = System.Text.Encoding.Default.GetBytes(exsql);
//注意字符集的选择,不合适的字符集只会导致乱码
//Byte[] info = new UTF8Encoding(true).GetBytes(exsql);
fs.Write(info, 0, info.Length);
this.progressBar2.Value = ((i + 1) / countSize) * this.progressBar2.Maximum;
Application.DoEvents();
}
fs.Close();

return strGenSql;
//}
//catch (Exception)
//{

//throw;
//}

}

private string GetFormatValue(string fdValue, string fdType)
{
if (fdValue == "")
return GetNullValue(fdValue);
//“/”在mysql里是转意符,故要小心处理,“/n”在导入时可能产生乱码
if (fdType.IndexOf("Int") > -1)
return fdValue.Replace("'", "//'").Replace("/n", "/r/n");
else if (fdType.IndexOf("DateTime") > -1)
return "'" + fdValue.Replace("'", "//'").Replace("/n", "/r/n") + "'";
else
return "'" + fdValue.Replace("//", "").Replace("//'", "'").Replace("'", "//'").Replace("/n", "/r/n").Replace(""", "/"") + " ' "; //最后加空格是为了避免数据源里乱码的干扰,当完全导入后记得trim()一次
}

private string GetNullValue(string fdType)
{
switch (fdType)
{
case "int":
return "null";
break;
case "varchar":
return "''";
break;
default:
return "null";
break;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: