首页 > 编程 > C# > 正文

c#连接mdf文件示例分享

2020-01-24 02:45:58
字体:
来源:转载
供稿:网友

C#连接本地.mdf文件:项目中右键点击,新增――数据――基于服务的数据库,项目下直接生成.mdf数据库文件,后台(数据库的写入用参数传递):

复制代码 代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;

namespace ADO.NET
{
    class Program
    {
        static void Main(string[] args)
        {
            //SQLServer 附加mdf文件
            string dataDir = AppDomain.CurrentDomain.BaseDirectory;
            if (dataDir.EndsWith(@"/bin/Debug/") || dataDir.EndsWith(@"/bin/Release/"))
            {
                dataDir = System.IO.Directory.GetParent(dataDir).Parent.Parent.FullName;
                AppDomain.CurrentDomain.SetData("DataDirectory", dataDir);
            }
            using (SqlConnection conn = new SqlConnection(@"Data Source=./SQLEXPRESS;AttachDbFilename=|DataDirectory|/Database1.mdf;Integrated Security=True;User Instance=True"))
            {
                conn.Open();
                //写入一条数据
                string strUserName = "作业本";
                string strPWD = "Ab123456";

                using (SqlCommand sqlCmd = conn.CreateCommand())
                {
                    sqlCmd.CommandText = "insert into Mytable1(Name,Password) values (@UserName,@PWD) ";//连接字符串进行参数化
                    SqlParameter[] sqlPara = new SqlParameter[] {
                    new SqlParameter("UserName",strUserName),
                    new SqlParameter("PWD",strPWD)
                    };
                    sqlCmd.Parameters.AddRange(sqlPara); //把Paramerter 数组参数添加到sqlCmd中
                    sqlCmd.ExecuteNonQuery();
                    Console.WriteLine("Insert OK");
                }

                //从表中读取数据
                string strRead = "SELECT   ID, Name, Password FROM      MyTable1 ";
                using (SqlCommand sqlCmd = new SqlCommand(strRead, conn))
                {
                    //sqlDataReader 逐行读取数据
                    using (SqlDataReader sdr = sqlCmd.ExecuteReader())
                    {
                        while (sdr.Read())
                        {

                            int id = sdr.GetInt32(sdr.GetOrdinal("ID"));  //sdr.GetOrdinal 获取列的序号
                            string Name = sdr.GetString(sdr.GetOrdinal("Name"));
                            bool PWD = sdr.IsDBNull(sdr.GetOrdinal("Password"));
                            Console.WriteLine("ID:{0},Name:{1},PWD:{2}", id, Name, PWD);
                            Console.WriteLine(sdr.GetString(1));
                        }
                    }
                }
                conn.Close();//此处可以省略,Dispose()方法会自动检查
            }
        }
    }
}

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表