代码之家  ›  专栏  ›  技术社区  ›  user287745

我想获得以下数据库信息,请建议[关闭]

  •  0
  • user287745  · 技术社区  · 15 年前

    我需要写一个代码,

    • 创建数据库
    • 创建四个表
    • 创建主键
    • 创建外键
    • 以及诸如int或boolean或string等类型的约束

    是的,我知道W3C Shools有SQL代码,但问题是我首先需要检测这些代码是否存在。

    这对我来说是个大问题。

    我尝试使用SQL异常,但它没有提供对异常进行分类的方法——比如databasetherexception——tablealreadytherexception.。

    因此,请为上述目的提供一些编码示例或链接,

    注:是的,我可以用google搜索,但是里面充满了示例和代码,太混乱了,所以希望能有直接的专业示例。

    我正在使用的代码类型的示例

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Data.SqlClient;
    using System.Data;
    
    public partial class Making_DB : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            //check or make the db
            MakeDB();
            CheckDB();
        }
    
        public void CheckDB()
        {
            try
            {
                string Data_source = @"Data Source=A-63A9D4D7E7834\SECOND;";
                string Initial_Catalog = @"Initial Catalog=master;";
                string User = @"User ID=sa;";
                string Password = @"Password=two";
    
                string full_con = Data_source + Initial_Catalog + User + Password;
    
                SqlConnection connection = new SqlConnection(full_con);
    
                connection.Open();
    
                SqlDataAdapter DBcreatingAdaptor = new SqlDataAdapter();
                DataSet ds2 = new DataSet();
                SqlCommand CheckDB = new SqlCommand("select * from sys.databases where name = 'my_db'", connection);
                DBcreatingAdaptor.SelectCommand = CheckDB;
                DBcreatingAdaptor.Fill(ds2);
                GridView1.DataSource = ds2;
                GridView1.DataBind();   // do not forget this//
                Response.Write("<br />WORKING(shows zero if db not there) checking by gridview rows: " + GridView1.Rows.Count.ToString());
                Response.Write("<br />NOT WORKING(keeps on showing one always!) checking by dataset tables: " + ds2.Tables.Count.ToString());
                DBcreatingAdaptor.Dispose();
                connection.Close();
    
                //Inaccesible due to protection level. Why??
                //SqlDataReader reader = new SqlDataReader(CheckDB, CommandBehavior.Default);
            }//try
            catch (Exception e)
            {
                Response.Write("   checking::    " +  e.Message);
            }//catch
        }//check db
    
        public void MakeDB()
        {
            try
            {
                string Data_source = @"Data Source=A-63A9D4D7E7834\SECOND;";
                //string Initial_Catalog = @"Initial Catalog=replicate;";
                string User = @"User ID=sa;";
                string Password = @"Password=two";
    
                string full_con = Data_source + User + Password;
    
                SqlConnection connection = new SqlConnection(full_con);
    
                connection.Open();
    
                //SqlCommand numberofrecords = new SqlCommand("SELECT COUNT(*) FROM dbo.Table_1", connection);
                SqlCommand CreateDB = new SqlCommand("CREATE DATABASE my_db", connection);
    
                //DataSet ds2 = new DataSet();
    
                SqlDataAdapter DBcreatingAdaptor = new SqlDataAdapter();
                DBcreatingAdaptor.SelectCommand = CreateDB;
                DBcreatingAdaptor.SelectCommand.ExecuteNonQuery();
    
                //check for existance
                //select * from sys.databases where name = 'my_db'
    
                DataSet ds2 = new DataSet();
                SqlCommand CheckDB = new SqlCommand(" select * from sys.databases where name = 'my_db'", connection);
                DBcreatingAdaptor.SelectCommand = CheckDB;
                //DBcreatingAdaptor.SelectCommand.ExecuteReader();
                DBcreatingAdaptor.Fill(ds2);
                GridView1.DataSource = ds2;
    
                //if not make it
            }//try
            catch (Exception e)
            {
                Response.Write("<br /> createing db error:  " + e.Message);
            }//catch
        }//make db
    }
    
    3 回复  |  直到 11 年前
        1
  •  3
  •   marc_s MisterSmith    15 年前

    正如我在评论中提到的那样-我会的 从未 从这样的函数直接写出响应流!返回包含错误消息或其他内容的字符串-但执行 不是 直接写入流或屏幕。

    你应该使用最好的包装方法 SqlConnection SqlCommand 进入之内 using(...){.....} 块以确保它们得到正确处置。另外,在代码中填充一个网格视图是非常糟糕的——您混合了数据库访问(后端)代码和UI前端代码——这是非常糟糕的选择。为什么不能将数据表传回,然后在UI前端代码中将其绑定到网格中??

    public DataTable CheckDB()
    {
        DataTable result = new DataTable();
    
        try
        {
            string connectionString = 
              string.Format("server={0};database={1};user id={2};pwd={3}"
                            "A-63A9D4D7E7834\SECOND", "master", "sa", "two"); 
    
            string checkQuery = "SELECT * FROM sys.databases WHERE name = 'my_db'";
    
            using(SqlConnection _con = new SqlConnection(connectionString))
            using(SqlCommand _cmd = new SqlCommand(checkQuery, _con))
            {
                SqlDataAdapter DBcreatingAdaptor = new SqlDataAdapter(_cmd);
                DBcreatingAdaptor.Fill(_result);
            }
        }//try
        catch (SqlException e)
        {
             // you can inspect the SqlException.Errors collection and 
             // get **VERY** detailed description of what went wrong,
             // including explicit SQL Server error codes which are 
             // unique to each error
        }//catch
    
        return result;
    }//check db
    

    还有-你在做 MakeDB() 方法太复杂了-为什么是表适配器?你只需要一个 Sql命令 要执行SQL命令,您已经有了一个方法来检查数据库是否存在。

    public void MakeDB()
    {
        try
        {
            string connectionString = 
              string.Format("server={0};database={1};user id={2};pwd={3}"
                            "A-63A9D4D7E7834\SECOND", "master", "sa", "two"); 
    
            string createDBQuery = "CREATE DATABASE my_db";
    
            using(SqlConnection _con = new SqlConnection(connectionString))
            using(SqlCommand _cmd = new SqlCommand(createDBQuery, _con))
            { 
                _con.Open();
                _cmd.ExecuteNonQuery();
                _con.Close();
            }
        }//try
        catch (SqlException e)
        {
           // check the detailed errors 
           // error.Number = 1801 : "database already exists" (choose another name)
           // error.Number = 102: invalid syntax (probably invalid db name)
           foreach (SqlError error in e.Errors)
           {
              string msg = string.Format("{0}/{1}: {2}", error.Number, error.Class, error.Message);
           }
        }//catch
    }//make db
    
        2
  •  1
  •   Community Mohan Dere    9 年前

    我非常肯定这和 the other question -不过,在我看来,你是从错误的角度来看待这个问题的。

    我会把它写成TSQL脚本,利用 EXEC 为了避免检查程序出现问题,例如:

    USE [master]
    if not exists ( ... database ...)
    begin
        print 'creating database...'   
        exec ('...create database...')
    end
    GO
    USE [database]
    if not exists( ... check schema tables for 1st thing ... )
    begin
        print 'Creating 1st thing...'
        exec ('...create 1st thing...')
    end
    if not exists( ... check schema tables for 2nd thing ... )
    begin
        print 'Creating 2nd thing...'
        exec ('...create 2nd thing...')
    end
    if not exists( ... check schema tables for 3rd thing ... )
    begin
        print 'Creating 3rd thing...'
        exec ('...create 3rd thing...')
    end
    

    然后,您可以随着模式的更改逐步扩展这个脚本,您所需要做的就是重新运行脚本,以便它更新数据库。

        3
  •  0
  •   Dewfy    15 年前

    可能不是您直接想要的,但为了方便从.NET创建和填充数据库,请查看广泛迁移工具的使用情况。我的首选项(Migrator.net),但可以在那里找到完整的评论: http://flux88.com/blog/net-database-migration-tool-roundup/