关闭

c# 创建SQL Server2005数据库及建表

标签: sql数据库创建C#
4490人阅读 评论(0) 收藏 举报
分类:

创建数据库代码,先判断有没有数据库,没有则创建,废话不多说,代码如下:

        private const string DB_NAME = @"safety_hidden";
        private const string DB_PATH = @"E:\";
        private string ConnectionString = @"Integrated Security=SSPI;Initial Catalog=" + DB_NAME + @";Data Source=.;";
        private SqlConnection conn = null;
        private SqlCommand cmd = null;
        private string sql = null;
        public SQLDeal()
        { }
        /// <summary>
        /// 创建数据库
        /// </summary>
        /// <param name="name">数据库名字</param>
        /// <param name="path">数据库路径</param>
        public void CreateDB()
        {
            string newConnectionString = @"Integrated Security=SSPI;Initial Catalog=;Data Source=.;";
            conn = new SqlConnection(newConnectionString);
            if (conn.State != ConnectionState.Open)
                conn.Open();
            sql = "if not exists(select * From master.dbo.sysdatabases where name='" + DB_NAME + "')" + "CREATE DATABASE " + DB_NAME + " ON PRIMARY" + "(name=" + DB_NAME + ",filename = '" + DB_PATH + DB_NAME + ".mdf', size=3," +
"maxsize=5,filegrowth=10%)log on" + "(name=" + DB_NAME + "_log,filename='" + DB_PATH + DB_NAME + "_log.ldf',size=3," + "maxsize=20,filegrowth=1)";
            cmd = new SqlCommand(sql,conn);
            try
            {
                cmd.ExecuteNonQuery();
            }
            catch (SqlException sqle)
            {
                Console.WriteLine(sqle.Message.ToString());
            }
             finally
            { 
                if(conn.State==ConnectionState.Open)
                       conn.Close();
                conn.Dispose();
            }
            
        }

        /// <summary>
        /// 创建数据库
        /// </summary>
        /// <param name="name">数据库名字</param>
        /// <param name="path">数据库路径</param>
        public bool CreateTable()
        {
            conn = new SqlConnection(ConnectionString);
            if (conn.State == ConnectionState.Open)
                conn.Close();
            sql = @"CREATE TABLE Big"+"(ID int identity primary key,"+"BigName varchar(30))";
            conn.Open();
            cmd = new SqlCommand(sql, conn);
            try
            {
                cmd.ExecuteNonQuery();
            }
            catch (SqlException ex)
            {
                Console.WriteLine(ex.Message.ToString());
            }
            finally
            {
                if (conn.State == ConnectionState.Open)
                    conn.Close();
                conn.Dispose();
            }
            return true;
        }

 转载请标明出处http://blog.csdn.net/jasonhds/版权所有,翻版必究~谢谢合作!


3
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:55648次
    • 积分:1002
    • 等级:
    • 排名:千里之外
    • 原创:44篇
    • 转载:2篇
    • 译文:0篇
    • 评论:1条