[英]SQL Check if table Exists in C#, if not create
我想我已经看到几乎所有与这个问题相关的页面,最有可能的答案是检查 SQL 表是否存在但并没有真正理解它。 这是我得到的:
private void select_btn_Click(object sender, EventArgs e)
{
string theDate = dateTimePicker1.Value.ToString("dd-MM-yyyy");
SqlConnection SC = new SqlConnection("Data Source=ruudpc;Initial Catalog=leden;Integrated Security=True");
SqlCommand DateCheck = new SqlCommand("SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = '" + theDate + "'");
}
现在我想要 DateCheck.ExecuteScalar() 的返回值; 这可以告诉我它是否存在,可能很简单。
编辑
不管 sql 注入部分如何,对于某些这个问题是有帮助的,动态创建表通常是不好的做法,我建议您重新考虑您的 ERD。 就是说。
使用 IF EXISTS T-SQL
private void select_btn_Click(object sender, EventArgs e)
{
string theDate = dateTimePicker1.Value.ToString("dd-MM-yyyy");
// Enclose the connection inside a using statement to close and dispose
// when you don't need anymore the connection (to free local and server resources)
using(SqlConnection SC = new SqlConnection("Data Source=ruudpc;Initial Catalog=leden;Integrated Security=True"))
{
// Sql command with parameter
string cmdText = @"IF EXISTS(SELECT * FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME=@name) SELECT 1 ELSE SELECT 0";
SC.Open();
SqlCommand DateCheck = new SqlCommand(cmdText, SC);
// Add the parameter value to the command parameters collection
DateCheck.Parameters.Add("@name", SqlDbType.NVarChar).Value = theDate
// IF EXISTS returns the SELECT 1 if the table exists or SELECT 0 if not
int x = Convert.ToInt32(DateCheck.ExecuteScalar());
if (x == 1)
MessageBox.Show("Table exists for date " + theDate);
else
MessageBox.Show("Table doesn't exist for date " + theDate);
}
}
你写代码的方式会导致sql注入攻击。参数化的SQL语句是避免SQL注入攻击的简单方法,也是一个很好的编码实践
CREATE PROCEDURE checkTableExist
@theDate varchar(10)
AS
SET NOCOUNT ON;
IF EXISTS(SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME=@theDate) SELECT 1 ELSE SELECT 0
C# 代码
try
{
string theDate = dateTimePicker1.Value.ToString("dd-MM-yyyy");
sqlConnection = new SqlConnection(dbConnectionString);
SqlCommand command = new SqlCommand("checkTableExist", sqlConnection);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add("@theDate", SqlDbType.VarChar).Value = dateTimePicker1.Value.ToString("dd-MM-yyyy");
sqlConnection.Open();
int result = (Int32)command.ExecuteScalar();
sqlConnection.Close();
if (result == 1)
return true;//or any message
else
return false;
}
catch (SqlException ex)
{
Console.WriteLine("SQL Error" + ex.Message.ToString());
return false;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.