.Net_把文件数据添加到数据库中(面试题)
时间:2021-07-01 10:21:17
帮助过:10人阅读
void Main(
string[] args)
{
//把文件数据读取到数组中
string[] str=File.ReadAllLines(
@"C:\Users\Administrator\Desktop\数据文件.txt",Encoding.Default);
//遍历数组
foreach (
var s
in str)
{
//分割字符串
string[] file= s.Split(
new char[]{
‘|‘}, StringSplitOptions.RemoveEmptyEntries);
//sql语句
string sql =
"INSERT INTO dbo.test_2(number, moneys, name)VALUES(@number,@moneys,@name);";
//sql参数
SqlParameter[] para =
{
new SqlParameter(
"@number",SqlDbType.NVarChar),
new SqlParameter(
"@moneys",SqlDbType.Int),
new SqlParameter(
"@name",SqlDbType.NVarChar),
};
para[0].Value = file[
0];
para[1].Value = Convert.ToInt32(file[
1]);
para[2].Value = file[
2];
//数据库操作
using (SqlConnection conn =
new SqlConnection(
"Data Source=.;Initial Catalog=Test;Persist Security Info=True;User ID=sa;Password=123"))
{
using (SqlCommand comm =
new SqlCommand(sql,conn))
{
if (para!=
null)
{
comm.Parameters.AddRange(para);
}
if (conn.State==
ConnectionState.Closed)
{
conn.Open();
}
int i=
comm.ExecuteNonQuery();
if (i>
0)
{
Console.WriteLine("插入成功");
}
}
}
}
Console.ReadKey();
}
View Code
.Net_把文件数据添加到数据库中(面试题)
标签: