日期:2014-05-19  浏览次数:20962 次

如何c#用ADO.NET将数据写入sql数据库
已经建立了一个sql   server数据库data.mdf
客户表   custom中有字段   "客户名 ", "联系方式 ", "住址 "
从custom.txt读取数据,如 "张三,135******,团结街**号 "
想写入custom表中,用ADO.NET如何实现!

------解决方案--------------------
using System;
using System.Data;
using System.Data.SqlClient;
using System.IO;

namespace ConsoleDemo
{
/// <summary>
/// Test 的摘要说明。
/// </summary>
public class Test
{
public static void Main()
{
FileInfo f = new FileInfo( "custom.txt ");
StreamReader sr = f.OpenText();

SqlConnection cn = new SqlConnection( "Server=.;uid=sa;pwd=;database=data ");;

string insertCmd = "insert into custom values (@name, @phone, @address) ";

char delimChar = ', ';
string [] split = null;

string strTemp = sr.ReadLine();
while(strTemp != null)
{
split = strTemp.Split(delimChar);
SqlCommand cmd = new SqlCommand(insertCmd, cn);

cmd.Parameters.Add( "@name ", SqlDbType.VarChar).Value = split[0];
cmd.Parameters.Add( "@phone ", SqlDbType.VarChar).Value = split[1];
cmd.Parameters.Add( "@address ", SqlDbType.VarChar).Value = split[2];
cn.Open();
try
{
cmd.ExecuteNonQuery();
}
catch(System.Data.SqlClient.SqlException e)
{
Console.WriteLine(e.Message);
}
cn.Close();
strTemp = sr.ReadLine();
}
sr.Close();
}
}
}

------解决方案--------------------
//这个处理了中文

using System;
using System.Data;
using System.Data.SqlClient;
using System.IO;

public class Test
{
public static void Main()
{
StreamReader sr = new StreamReader(new FileStream( "custom.txt ", FileMode.Open, FileAccess.Read), System.Text.Encoding.Default);

SqlConnection cn = new SqlConnection( "Server=.;uid=sa;pwd=;database=data ");;

string insertCmd = "insert into custom values (@name, @phone, @address) ";

char delimChar = ', ';
string [] split = null;

string strTemp = sr.ReadLine();
while(strTemp != null)
{
split = strTemp.Split(delimChar);
SqlCommand cmd = new SqlCommand(insertCmd, cn);

cmd.Parameters.Add( "@name ", SqlDbType.VarChar).Value = split[0];
cmd.Parameters.Add( "@phone ", SqlDbType.VarChar).Value = split[1];
cmd.Parameters.Add( "@address ", SqlDbType.VarChar).Value = split[2];
cn.Open();
try
{
cmd.ExecuteNonQuery();
}
catch(System.Data.SqlClient.SqlException e)
{
Console.WriteLine(e.Message);
}
cn.Close();
strTemp = sr.ReadLine();
}
sr.Close();
}
}