How to connect to database with C#

Method to connect to SQL Server database:

1. Reference the System.Data.SqlClient namespace in the program

2. Write a connection string in the format: Data Source=server name; Initial Catalog=database name; User ID=user name; Password=password Among them, Data Source specifies the server name, Initial Catalog specifies the database name, User ID and Password respectively Specify the username and password for the connection.

3. Create a SqlConnection object and pass in the connection string parameters, as follows: SqlConnection conn = new SqlConnection("Connection string");

4. Open the database connection conn.Open();

5. Execute SQL statement or stored procedure SqlCommand cmd=new SqlCommand("SQL statement or stored procedure name", conn); //Execute SQL statement or stored procedure 6. Close the database connection conn.Close(); The following is a complete Sample code to connect to the database:

using System;

using System.Data.SqlClient;

namespace ConsoleApplication1

{

    class Program

    {

        static void Main(string[] args)

        {

            string connStr="Data Source=.;Initial Catalog=test;User ID=sa;Password=123456";

            SqlConnection conn=new SqlConnection(connStr);

            try

            {

                conn.Open();   

                SqlCommand cmd=new SqlCommand("insert into t_user values('test','123456')",conn);

                cmd.ExecuteNonQuery();             

                Console.WriteLine("数据插入成功!");

            }

            catch(Exception ex)

            {

                Console.WriteLine(ex.Message);

            }

            finally

            {

                conn.Close();

            }

            Console.ReadKey();

        }

    }

}

Guess you like

Origin blog.csdn.net/w909252427/article/details/129713237