首先,我们在程序中动态地创建SQL Server数据库。
我们将数据库创建在C:\mysql目录下,所以读者要练习该实例的话得先在C:下创建一个名为mysql的文件夹,否则会出错!创建数据库的关键是函数中的sql对象,通过该对象我们指定了数据库文件的一些基本属性。之后,我们新创建了一个SqlCommand对象,通过该对象我们 就实际完成了对数据库的 *** 作。函数的实现如下:
private void button1_Click(object sender, SystemEventArgs e)
{
// 打开数据库连接
if( connState != ConnectionStateOpen)
connOpen();
string sql = "CREATE DATABASE mydb ON PRIMARY"
+"(name=test_data, filename = 'C:\\mysql\\mydb_datamdf', size=3,"
+"maxsize=5, filegrowth=10%) log on"
+"(name=mydbb_log, filename='C:\\mysql\\mydb_logldf',size=3,"
+"maxsize=20,filegrowth=1)";
cmd = new SqlCommand(sql, conn);
try { cmdExecuteNonQuery(); }
catch(SqlException ae)
{
MessageBoxShow(aeMessageToString());
}
}
其次,我们通过CREATE TABLE语句创建基本表,并向该表中添加4条数据。函数的实现如下:
private void button2_Click(object sender, SystemEventArgs e)
{
// 打开数据库连接
if( connState == ConnectionStateOpen)
connClose();
ConnectionString ="Integrated Security=SSPI;" + "Initial Catalog=mydb;" + "Data Source=localhost;";
connConnectionString = ConnectionString;
connOpen();
sql = "CREATE TABLE myTable"+ "(myId INTEGER CONSTRAINT PKeyMyId PRIMARY KEY,"
+ "myName CHAR(50), myAddress CHAR(255), myBalance FLOAT)";
cmd = new SqlCommand(sql, conn);
try {
cmdExecuteNonQuery(); // 向表中添加记录
sql = "INSERT INTO myTable(myId, myName, myAddress, myBalance) "+ "VALUES (1001, 'Puneet Nehra', 'A 449 Sect 19, DELHI', 2398 ) " ;
cmd = new SqlCommand(sql, conn);
cmdExecuteNonQuery();
sql = "INSERT INTO myTable(myId, myName,myAddress, myBalance) "+ "VALUES (1002, 'Anoop Singh', 'Lodi Road, DELHI', 35364) " ;
cmd = new SqlCommand(sql, conn);
cmdExecuteNonQuery();
sql = "INSERT INTO myTable(myId, myName, myAddress, myBalance) "+ "VALUES (1003, 'Rakesh M', 'Nag Chowk, Jabalpur MP', 4343) " ;
cmd = new SqlCommand(sql, conn);
cmdExecuteNonQuery();
sql = "INSERT INTO myTable(myId, myName, myAddress, myBalance) "+ "VALUES (1004, 'Madan Kesh', '4th Street, Lane 3, DELHI', 2300) " ;
cmd = new SqlCommand(sql, conn);
cmdExecuteNonQuery(); }
catch(SqlException ae) { MessageBoxShow(aeMessageToString()); }
}
完成此 *** 作后,我们可以打开SQL SERVER的企业管理器,查看是否有我们创建的数据库和基本表。
以上就是关于怎么用c#代码在sql中建立新的数据库全部的内容,包括:怎么用c#代码在sql中建立新的数据库、、等相关内容解答,如果想了解更多相关内容,可以关注我们,你们的支持是我们更新的动力!
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)