public void GeneralSqlScript() { DataTable dt = new DataTable("表名"); using (SqlConnection con = new SqlConnection("连接字符串")) { using (SqlDataAdapter adapter = new SqlDataAdapter("select * from 表名", con)) { adapter.Fill(dt); } } string colsStr = ""; foreach(DataColumn col in dt.Columns) { colsStr += col.ColumnName + ","; } if (colsStr.Length > 0) { colsStr = colsStr.Remove(colsStr.Length - 1); } using (System.IO.FileStream fs = new FileStream("D:\\db.sql", FileMode.OpenOrCreate)) {//构造sql脚本 保存到 "D:\\db.sql"文件 using (System.IO.StreamWriter sw = new StreamWriter(fs, Encoding.Default)) { foreach (DataRow dr in dt.Rows) { string valuesStr = ""; for (int i = 0; i < dt.Columns.Count; i++) { if (dr[i] == System.DBNull.Value) { valuesStr += "null"; } else { switch (dt.Columns[i].DataType.Name) { case "String": case "Boolean": valuesStr += "'" + dr[i].ToString() + "'"; break; case "Byte[]": valuesStr += "'" + Convert.ToBase64String(dr[i] as byte[]) + "'"; break; default: valuesStr += dr[i].ToString(); break; //如果还有其他其他特殊类型,自行添加转换字符串的方式 } } if(i != dt.Columns.Count -1) { valuesStr += ","; } } sw.WriteLine(string.Format("insert into {0}({1}) values({2});", dt.TableName, colsStr, valuesStr)); } } } }