如何創建數據庫?

/*

 如何創建數據庫?

 *

 * 1.創建string str = 接收連接路徑

 *

 * 2.創建連接數據庫的對象(SqlConnection,傳入連接路徑)

 *   |--SqlConnection conn = new SqlConnection(str)

 *

 * 3.編寫SQL語句(創建string sql"SQL語句"

 *

 * 4.創建執行對象(SqlCommand)

 *  |--SqlCommand cmd = new SqlCommand(sql語句,SqlConnection連接對象)

 *  

 * 5.打開數據庫連接對象.open

 *  |--conn.open();

 *  

 * 6.執行對象ExecuteNonQuery()

 *  |--cmd.ExecuteNonQuery();

 *  

 * 7.關閉數據庫連接對象.close

 *  |--conn.close();

 *  

 */

 

 

namespace SQL數據庫

{

    class Program

    {

        static void Main(string[] args)

        {

            Console.WriteLine("請輸入姓名:");

            stringname = Console.ReadLine();

            Console.WriteLine("請輸入年齡:");

            stringage = Console.ReadLine();

            Console.WriteLine("請輸入電話:");

            stringphone = Console.ReadLine();

           

//1.連接字符串

string str = @"DataSource=e420;Initial Catalog=tt;Integrated Security=True";

 

//2.創建連接對象

SqlConnection conn = new SqlConnection(str);//()傳入的是連接路徑

 

//3.編寫SQL語句

//string sql = "insert intostudent(student.name,student.age,student.phone)values('王五',33,'13343243432')";

string sql = string.Format("insert intostudent(student.name,student.age,student.phone)values('{0}',{1},'{2}')", name, age, phone);

           

//4.創建 執行語句對象

SqlCommand cmd = new SqlCommand(sql, conn);//傳入的是sql語句連接對象

 

//5.打開數據庫連接

conn.Open();

 

//6.執行語句

cmd.ExecuteNonQuery();

 

//7.關閉數據庫連接

conn.Close();

          

Console.ReadKey();
發佈了38 篇原創文章 · 獲贊 4 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章