C# 将txt文件的数据库元组导入数据库,代码实现

xiaoxiao2021-02-28  58

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Data.SqlClient; using System.IO; namespace 导入数据 { class Program { static void Main(string[] args) { string str = "Data Source=LENOVO-PC;Initial Catalog=MyDatabase;Integrated Security=True"; int n = -1;//判断是否导入成功 using (StreamReader sr=new StreamReader("1.txt")) { string line = sr.ReadLine();//第一行列名不要 using (SqlConnection sco = new SqlConnection(str)) { string sql = "insert into users1(logName, logPassWord) values(@logName,@logPassWord)"; //用参数代替拼接,防止SQL注入漏洞 SqlParameter[] ps = { new SqlParameter("@logName",System.Data.SqlDbType.VarChar), new SqlParameter("@logPassWord",System.Data.SqlDbType.VarChar) }; sco.Open(); using (SqlCommand scd = new SqlCommand(sql, sco)) { scd.Parameters.AddRange(ps); while ((line=sr.ReadLine())!=null) { string[] texts = line.Split(new char[] { ','},StringSplitOptions.RemoveEmptyEntries); ps[0].Value = texts[0]; ps[1].Value = texts[1]; n = scd.ExecuteNonQuery(); } } sco.Close(); } } if (n > 0) { Console.WriteLine("导入成功!"); } else { Console.WriteLine("导入失败!"); } Console.ReadKey(); } } }
转载请注明原文地址: https://www.6miu.com/read-81684.html

最新回复(0)