SoFunction
Updated on 2025-03-07

C# Connect mdf file example sharing


using System;
using ;
using ;
using ;
using ;

namespace
{
    class Program
    {
        static void Main(string[] args)
        {
//SQLServer attaches mdf file
            string dataDir = ;
            if ((@"\bin\Debug\") || (@"\bin\Release\"))
            {
                dataDir = (dataDir).;
                ("DataDirectory", dataDir);
            }
            using (SqlConnection conn = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\;Integrated Security=True;User Instance=True"))
            {
                ();
//Write a data
string strUserName = "Homebook";
                string strPWD = "Ab123456";

                using (SqlCommand sqlCmd = ())
                {
= "insert into Mytable1(Name,Password) values ​​(@UserName,@PWD) ";//Connect string for parameterization
                    SqlParameter[] sqlPara = new SqlParameter[] {
                    new SqlParameter("UserName",strUserName),
                    new SqlParameter("PWD",strPWD)
                    };
(sqlPara); //Add Paramerter array parameters to sqlCmd
                    ();
                    ("Insert OK");
                }

//Read data from the table
                string strRead = "SELECT   ID, Name, Password FROM      MyTable1 ";
                using (SqlCommand sqlCmd = new SqlCommand(strRead, conn))
                {
//sqlDataReader reads data line by line
                    using (SqlDataReader sdr = ())
                    {
                        while (())
                        {

int id = sdr.GetInt32(("ID")); // Get the column number
                            string Name = (("Name"));
                            bool PWD = (("Password"));
                            ("ID:{0},Name:{1},PWD:{2}", id, Name, PWD);
                            ((1));
                        }
                    }
                }
();//It can be omitted here, the Dispose() method will automatically check
            }
        }
    }
}