亲宝软件园·资讯

展开

c#连接mdf文件 c#连接mdf文件示例分享

人气:1
想了解c#连接mdf文件示例讲解的相关内容吗,在本文为您仔细讲解c#连接mdf文件的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:c#,mdf文件,下面大家一起来学习吧。

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()方法会自动检查
            }
        }
    }
}

加载全部内容

相关教程
猜你喜欢
用户评论