1.鏈接到數據庫sql
1 public static SqlConnection conn; 2 //本地數據庫 .\\SQLEXPRESS 3 conn = new SqlConnection("Initial Catalog=student;Data Source=XS-YGD\\SQLEXPRESS;User ID='cam';Password='xs123';Connect Timeout=30"); 4 //conn = new SqlConnection("Data Source = .\\SQLEXPRESS;Initial Catalog=Student;Integrated Security=True");//Initial Catalog後面跟你數據庫的名字 5 conn.Open();
2,將數據庫導入到dataGridView中數據庫
1 // 打開數據庫鏈接 2 if (conn.State == ConnectionState.Open) 3 conn.Close(); 4 ConnectionString = "Integrated Security=SSPI;" + 5 "Initial Catalog = " + DBName + ";" + 6 "Data Source=.\\SQLEXPRESS;"; 7 conn.ConnectionString = ConnectionString; 8 conn.Open();
1 // 建立數據適配器 2 SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM " + TableName , conn); 3 // 建立一個數據集對象並填充數據,而後將數據顯示在DataGrid控件中 4 DataSet ds = new DataSet(TableName); 5 da.Fill(ds, TableName); 6 dataGridView1.DataSource = ds.Tables[TableName].DefaultView;
3,執行數據庫命令spa
1 // <summary> 2 /// 執行數據庫命令 3 /// </summary> 4 /// <param name="sql"></param> 5 private bool ExecuteSQLStmt(string DBName, string sql) 6 { 7 // 打開數據庫鏈接 8 if (conn.State == ConnectionState.Open) 9 conn.Close(); 10 ConnectionString = "Integrated Security = SSPI;" + "Initial Catalog = " + DBName + ";" + "Data Source =.\\SQLEXPRESS;"; 11 conn.ConnectionString = ConnectionString; 12 conn.Open(); 13 SqlCommand cmd = new SqlCommand(sql, conn); 14 try 15 { 16 cmd.ExecuteNonQuery(); 17 } 18 catch (SqlException ae) 19 { 20 MessageBox.Show(ae.Message.ToString()); 21 return false; 22 } 23 return true; 24 }
4,添加列code
1 string sql = "alter table " + TableName + " ADD " + colName + " " + Type + " not null default ('" + defaultdate + "') with values"; 2 ExecuteSQLStmt(DBName, sql);
5,添加主鍵對象
1 string sql = "alter table " + TableName + " add CONSTRAINT " + PrimaryKeyName + " primary key(" + ColName + ")"; 2 return ExecuteSQLStmt(DBName, sql);
6,綁定默認值blog
1 //綁定默認值 2 public bool BindDefault(string DBName, string DefaultName, string TableName, string colName) 3 { 4 string sql = "EXEC sp_bindefault '" + DefaultName + "', '" + TableName + "." + colName + "'"; 5 return ExecuteSQLStmt(DBName, sql); 6 }
7,關閉數據庫cmd
1 if (conn.State == ConnectionState.Open) 2 conn.Close();