下面以以前写的一段代码为例
private void btout_Click(object sender, EventArgs e)
{
string source = @"Data Source=.\SQLEXPRESS;AttachDBFilename=|DataDirectory|\Database1(数据库名称).mdf;Integrated Security=True;User Instance=True";//连接字符串用于连接到本地数据库
记得在解决方案中添加本地数据库 要不然就
//string st = @"Data Source=HP-HP(主机名);Initial Catalog=(数据库名称);Persist Security Info=True;User ID=(登录名称);Password=(密码)"; 用于连接非本地数据库
using(SqlConnection conn = new SqlConnection(source)) //为数据库打开一个连接
{
conn.Open();
using(SqlCommand comm=conn.CreateCommand())//数据库进行操作过程
{
comm.CommandText = "select * from Table1 where name=@Name";//对数据库操作
comm.Parameters.Add(new SqlParameter("Name","kk"));//类似以占位符为@Name复制 ,可避免注入漏洞
comm.ExecuteNonQuery();//返回执行行数 必要操作
using(SqlDataReader read=comm.ExecuteReader())//对用数据库索引出的内容进行读操作
{
string a=null, b=null;
while (read.Read())
{
a = read.GetString(read.GetOrdinal("name"));
b = read.GetString(read.GetOrdinal("age"));
}
//--------------------------------------------------------------------------------------------------------------------------------------------
SaveFileDialog sfd = new SaveFileDialog();
if (sfd.ShowDialog() == DialogResult.OK)
{
using (FileStream fs = new FileStream(sfd.FileName,FileMode.Open))
{
using (StreamWriter sw=new StreamWriter(fs))
{
sw.Write(a);
sw.Write(b);
sw.Close();
fs.Close();
}
}
}
}
}
}
}