我需要编写一个代码,
是的我知道w3c shools有sql代码,但问题是我首先需要逐个检测这些东西是否存在。
这对我来说是一个很大的问题。
我尝试使用sql异常,但它没有提供对异常进行分类的方法 - 比如databasethereexception - tablealreadythereEXCEPTION ..
所以请为上述目的提供一些编码示例或链接,
注意:是的我可以谷歌,但它是完整的示例和代码,它太混乱,所以希望直接的专业示例
也是我正在使用的代码类型的示例
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
}
答案 0 :(得分:3)
正如我在评论中已经提到的那样 - 我会从不直接写出来自这样的函数的Response流!传回带有错误消息的字符串 - 但 NOT 直接写入流或屏幕。
您应该使用将SqlConnection
和SqlCommand
包裹到using(...){.....}
块中的最佳做法,以确保它们得到妥善处理。此外,从此代码中填充gridview非常糟糕 - 您正在混合数据库访问(后端)代码和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()
方法过于复杂 - 为什么表适配器?您只需要一个SqlCommand
来执行您的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
答案 1 :(得分:1)
我非常确定这与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
然后,您可以在架构更改时逐步扩展此脚本,您需要做的就是重新运行脚本以更新数据库。
答案 2 :(得分:0)
可能不是你想要的,而是为了方便数据库的创建和安装。人口来自.Net审查广泛迁移工具的使用情况。我的偏好(Migrator.NET)可以在那里找到完整的评论:http://flux88.com/blog/net-database-migration-tool-roundup/