Bootstrap

C# 用SQL新建数据库

1. 程序如下:

         string str = "Create Database " + "DBname";
         string con = "Data Source=10.0.0.249//sql2005;Initial Catalog=master;Persist Security Info=True;User ID=sa;Password=sa";
            SqlConnection myConn = new SqlConnection(con);

 

            SqlCommand myCommand = new SqlCommand(str, myConn);

            try
            {
                myConn.Open();
                myCommand.ExecuteNonQuery();

                Console.WriteLine("SQL 语句执行完成。", "MyProgram");
            }
            catch (System.Exception ex)
            {
                Console.WriteLine(ex.ToString(), "MyProgram");
            }
            finally
            {
                if (myConn.State == ConnectionState.Open)
                {
                    myConn.Close();
                }
            }


            con = "Data Source=10.0.0.249//sql2005;Initial Catalog=" + "DBName" + ";Persist Security Info=True;User ID=sa;Password=sa";
            str = "";
            StreamReader sr = new StreamReader("..//database.sql", System.Text.Encoding.GetEncoding("gb2312"));
           
            string s = "";
            while ((s = sr.ReadLine()) != null)
            {

                str += " " + s;

            }
           myConn = new SqlConnection(con);

 

            myCommand = new SqlCommand(str, myConn);

            try
            {
                myConn.Open();
                myCommand.ExecuteNonQuery();

                Console.WriteLine("SQL 语句执行完成。", "MyProgram");
            }
            catch (System.Exception ex)
            {
                Console.WriteLine(ex.ToString(), "MyProgram");
            }
            finally
            {
                if (myConn.State == ConnectionState.Open)
                {
                    myConn.Close();
                }
            }

 

2. SQL 脚本

if exists(select 1 from master..sysdatabases where name='example')

print 'DataBase existed'

else

print 'Database not existed'

 

IF Exists(Select 1 From sysObjects Where Name ='Userinfo' And Type In ('S','U'))

Print 'Exists Table'

Else
BEGIN
Print 'Not Exists Table'
CREATE TABLE Userinfo
(
Userid nvarchar(20) NOT NULL PRIMARY KEY,
Username nvarchar(20) NOT NULL
)
END

;