C Simple Connection to sql Database

  • 2021-10-16 02:26:05
  • OfStack

In this paper, an example is given to describe the simple connection method of C # to sql database. Share it for your reference, as follows:


using System;
using System.Collections.Generic;
using System.Text;
// Database operation object library 
using System.Data;
using System.Data.SqlClient;
using worddic;
namespace testDB
{
  class Program
  {
    static void Main(string[] args)
    {
      //char[] array = new char[2] ;
      string [] a = new string[2];
      FileOp words = new FileOp();
      words.openfile("worddic.txt");
      words.getwords(ref a);
      /* Console.WriteLine(" Please enter Data Source : ");
      string data_source = Console.ReadLine();
      Console.WriteLine(" Please enter Initial Catalog : ");
      string initial_catalog = Console.ReadLine();
      Console.WriteLine(" Please enter user id : ");
      string user_id = Console.ReadLine();
      Console.WriteLine(" Please enter pass word : ");
      string pword = Console.ReadLine();
      // Connection string 
      string strConn ="Data Source="+data_source+";Initial Catalog="+initial_catalog+";User ID="+user_id+";Password="+pword+"";//YourPwd Replace with the one you set sa Account password 
      */
      string strConn = "Data Source=HYPER-V-WIN2003\\SQLSRV2005;Initial Catalog=Mytest;User ID=sa;Password=sa";
      SqlConnection conn = null;
      SqlCommand sqlCmd = null;
      try
      {
        // Create connection Object 
        conn = new SqlConnection(strConn);
        // Open a database connection 
        conn.Open();
        // Create Transac Sql Command object 
        sqlCmd = conn.CreateCommand();
        // Create a table building statement 
        //sqlCmd.CommandText = "create table wordlist(wrongwords varchar(30),rightwords varchar(30),sign char(20),)";
        //sqlCmd.ExecuteScalar();
        while (a[0] != null) {
          sqlCmd.CommandText ="insert into wordlist(wrongwords,rightwords,sign) values('" + a[0] + "','" + a[1] + "',1 )";
          sqlCmd.ExecuteScalar();
          a[0] = null;
          a[1] = null;
          words.getwords(ref a);
        }
        words.fileclose();
        Console.WriteLine();
        // Print all records 
      }
      catch (SqlException e)
      {
        Console.WriteLine(e.Message);
      }
      finally
      {
        conn.Close();
      }
      Console.WriteLine(" When the program ends, press any key to exit ");
      Console.ReadKey();
    }
  }
}

For more readers interested in C # related content, please check the topics on this site: "Summary of XML File Operation Skills in C #", "C # Common Control Usage Tutorial", "WinForm Control Usage Tutorial", "C # Data Structure and Algorithm Tutorial", "C # Object-Oriented Programming Introduction Tutorial" and "C # Programming Thread Use Skills Summary"

I hope this article is helpful to everyone's C # programming.


Related articles: