刚写到一个程序,需要对SQL里面添加数据库和表.在网上找的资料不太全.特整理了一下.详细资料如下: //__________________创建数据库____________________ string ConnectionString = "Data Source=localhost;Integrated Security=True;Pooling=False"; SqlConnection conn = new SqlConnection(ConnectionString); conn.Open(); sql = "CREATE DATABASE clsky on primary(name = abc ,filename = 'e:\\clsky.mdf')"; SqlCommand cmd = new SqlCommand(sql, conn); cmd.ExecuteNonQuery(); MessageBox.Show("创建数据库成功!"); //_________________________________________________
//________________创建表___________________________
string ConnectionString1 = "Data Source=localhost;Initial Catalog=clsky;Integrated Security=True;Pooling=False"; SqlConnection conn1 = new SqlConnection(ConnectionString1); conn1.Open(); sql = "CREATE TABLE clsky"+ "(Id INTEGER CONSTRAINT PKeyMyId PRIMARY KEY,"+ "Name CHAR(50), Address CHAR(255), Balance FLOAT)"; SqlCommand cmd1 = new SqlCommand(sql, conn1); cmd1.ExecuteNonQuery(); MessageBox.Show("创建数据库成功!"); //__________________________________________________
//_______________删除表_____________ sql = "DROP TABLE clsky"; SqlCommand cmd2 = new SqlCommand(sql, conn1); cmd2.ExecuteNonQuery(); MessageBox.Show("删除表成功!"); conn1.Close(); conn.Close(); //_________________________________ 你如果还要删除此数据库.可以使用: string ConnectionString = "Data Source=localhost;Integrated Security=True;Pooling=False"; SqlConnection conn = new SqlConnection(ConnectionString); conn.Open(); string sql = "DROP DATABASE clsky "; SqlCommand cmd = new SqlCommand(sql, conn); cmd.ExecuteNonQuery();
|
请发表评论