using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LB_SmartVision
{
public class LB_SqlCommand
{
///
/// 连接字符串:指定 SQL Server 实例和数据库(实际会读取dll.config中的值来更新连接字符串)
///
public static string ConnectionString = "Data Source=localhost;Initial Catalog=master;Integrated Security=True;";
///
/// 判断指定列是否存在某值
///
/// 表名
/// 指定列名
/// 指定值
///
/// 值存在True
public static bool IsExist(string tableName, string columnName, string value, string connectionString = "")
{
if (string.IsNullOrEmpty(connectionString))
connectionString = ConnectionString;
// SQL 查询语句,检查 ProcessName 列是否存在指定的值
string sqlQuery = string.Format("SELECT CASE WHEN EXISTS (SELECT 1 FROM [{0}] " +
"WHERE [{1}] = @Value) THEN 1 ELSE 0 END", tableName, columnName);
// 创建 SQL 连接
using (SqlConnection connection = new SqlConnection(connectionString))
{
// 创建 SQL 命令
using (SqlCommand command = new SqlCommand(sqlQuery, connection))
{
// 添加参数,防止 SQL 注入
command.Parameters.AddWithValue("@Value", value);
// 打开连接
connection.Open();
// 执行查询并获取结果
int result = (int)command.ExecuteScalar();
// 如果 result == 1,表示存在该值;否则不存在
if (result == 1)
return true;
else
return false;
}
}
}
///
/// 判断指定表是否存在
///
/// 表名
///
/// 值存在True
public static bool IsExistTable(string tableName, string connectionString = "")
{
if (string.IsNullOrEmpty(connectionString))
connectionString = ConnectionString;
// SQL 查询语句,检查 ProcessName 列是否存在指定的值
string sqlQuery = $@"
SELECT COUNT(*)
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME = @TableName";
// 创建 SQL 连接
using (SqlConnection connection = new SqlConnection(connectionString))
{
// 创建 SQL 命令
using (SqlCommand command = new SqlCommand(sqlQuery, connection))
{
// 添加表名参数
command.Parameters.AddWithValue("@TableName", tableName);
// 打开连接
connection.Open();
// 执行查询并获取结果
int result = (int)command.ExecuteScalar();
// 如果 result > 0,表示存在该表;否则不存在
if (result > 0)
return true;
else
return false;
}
}
}
///
/// 重命名表
///
///
///
///
///
public static bool RenameTable(string oldTableName, string newTableName, string connectionString = "")
{
if (string.IsNullOrEmpty(connectionString))
connectionString = ConnectionString;
if (!IsExistTable(oldTableName))
return false;
// SQL 查询语句,检查 ProcessName 列是否存在指定的值
string sqlQuery = $"EXEC sp_rename '{oldTableName}', '{newTableName}'"; ;
// 创建 SQL 连接
using (SqlConnection connection = new SqlConnection(connectionString))
{
// 创建 SQL 命令
using (SqlCommand command = new SqlCommand(sqlQuery, connection))
{
// 打开连接
connection.Open();
// 执行查询并获取结果
int result = (int)command.ExecuteNonQuery();
// 如果 result == -1,表示重命名成功
if (result == -1)
return true;
else
return false;
}
}
}
///
/// 判断指定表是否存在
///
/// 表名
///
/// 值存在True
public static bool DeleteTable(string tableName, string connectionString = "")
{
if (string.IsNullOrEmpty(connectionString))
connectionString = ConnectionString;
// SQL 查询语句,检查 ProcessName 列是否存在指定的值
string sqlQuery = $"DROP TABLE IF EXISTS [{tableName}]";
// 创建 SQL 连接
using (SqlConnection connection = new SqlConnection(connectionString))
{
// 创建 SQL 命令
using (SqlCommand command = new SqlCommand(sqlQuery, connection))
{
// 打开连接
connection.Open();
// 执行查询并获取结果
int result = (int)command.ExecuteNonQuery();
// 如果 result = -1,表示存在该表移除成功
if (result == -1)
return true;
else
return false;
}
}
}
///
/// 获取所需的值通过索引指定列的指定值定位到所在行的指定列
///
/// 表名
/// 指定列名
/// 指定列值
/// 所需值的列名
///
/// 所需列值
public static string FindValueFromIndexName(string tableName, string indexName, string indexValue, string columnName, string connectionString = "")
{
try
{
if (string.IsNullOrEmpty(connectionString))
connectionString = ConnectionString;
// SQL 查询语句,检查 ProcessName 列是否存在指定的值
string sqlQuery = $"SELECT {columnName} FROM [{tableName}] WHERE {indexName} = @IndexValue";
string resultValue = string.Empty;
// 连接数据库并执行查询
using (SqlConnection connection = new SqlConnection(connectionString))
{
using (SqlCommand command = new SqlCommand(sqlQuery, connection))
{
// 添加参数以防止 SQL 注入
command.Parameters.AddWithValue("@IndexValue", indexValue);
// 打开连接
connection.Open();
// 执行查询并获取结果
var result = command.ExecuteScalar();
if (result != null)
{
resultValue = result.ToString();
}
}
}
return resultValue;
}
catch { return string.Empty; }
}
///
/// 删除指定行通过索引指定列的指定值
///
/// 表名
/// 指定列名
/// 指定列值
///
/// 删除成功True
public static bool DeleteRowFromIndexName(string tableName, string indexName, string indexValue, string connectionString = "")
{
try
{
if (string.IsNullOrEmpty(connectionString))
connectionString = ConnectionString;
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
// 删除指定行
string deleteQuery = string.Format("DELETE FROM [{0}] WHERE {1} = @indexValue", tableName, indexName);
using (SqlCommand cmd = new SqlCommand(deleteQuery, conn))
{
cmd.Parameters.AddWithValue("@indexValue", indexValue);
cmd.ExecuteNonQuery();
}
// 更新剩余行的 step
string updateQuery = string.Format(@"
WITH OrderedSteps AS (
SELECT {1}, ROW_NUMBER() OVER (ORDER BY {1}) AS NewValue
FROM [{0}]
)
UPDATE [{0}]
SET {1} = NewValue
FROM [{0}] s
JOIN OrderedSteps o ON s.{1} = o.{1};
", tableName, indexName);
using (SqlCommand cmd = new SqlCommand(updateQuery, conn))
{
cmd.ExecuteNonQuery();
}
return true;
}
}
catch { return false; }
}
///
/// 交换指定行的所有值通过索引指定列的指定值
///
/// 表名
/// 列名
/// 交换的列值
/// 被交换的列值
///
/// 交换成功True
public static bool SwapRowFromIndexName(string tableName, string swapName, string swapValue1, string swapValue2, string connectionString = "")
{
if (string.IsNullOrEmpty(connectionString))
connectionString = ConnectionString;
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
// 开始事务
SqlTransaction transaction = conn.BeginTransaction();
try
{
// 交换 step 为 3 和 4 的行
string swapQuery = string.Format(@"
BEGIN TRANSACTION;
UPDATE [{0}]
SET {1} = @SwapTempValue
WHERE {1} = @SwapValue1;
UPDATE [{0}]
SET {1} = @SwapValue1
WHERE {1} = @SwapValue2;
UPDATE [{0}]
SET {1} = @SwapValue2
WHERE {1} = @SwapTempValue;
COMMIT;", tableName, swapName);
using (SqlCommand cmd = new SqlCommand(swapQuery, conn, transaction))
{
// 添加参数
cmd.Parameters.AddWithValue("@SwapValue1", swapValue1);
cmd.Parameters.AddWithValue("@SwapValue2", swapValue2);
cmd.Parameters.AddWithValue("@SwapTempValue", Guid.NewGuid().ToString());
// 执行查询
cmd.ExecuteNonQuery();
}
// 提交事务
transaction.Commit();
return true;
}
catch (Exception ex)
{
Debug.WriteLine("交换失败,原因是:" + ex.Message.ToString());
// 出现异常时回滚事务
transaction.Rollback();
return false;
}
}
}
///
/// 更新指定列的值通过索引指定列的指定值
///
///
///
///
///
///
///
public static bool UpdataValueFromIndexName(string tableName, string oriValue, string newValue, string columnName, string connectionString = "")
{
if (string.IsNullOrEmpty(connectionString))
connectionString = ConnectionString;
// SQL 查询语句,检查 ProcessName 列是否存在指定的值
string sqlQuery = string.Format("UPDATE [{0}] SET {1} = @NewValue WHERE {1} = @OriValue", tableName, columnName);
string resultValue = string.Empty;
// 连接数据库并执行查询
using (SqlConnection connection = new SqlConnection(connectionString))
{
using (SqlCommand command = new SqlCommand(sqlQuery, connection))
{
// 参数化查询,防止 SQL 注入
command.Parameters.AddWithValue("@OriValue", oriValue); // 要替换的原始值
command.Parameters.AddWithValue("@NewValue", newValue); // 替换后的新值
// 打开连接
connection.Open();
// 执行更新操作
int rowsAffected = command.ExecuteNonQuery();
if (rowsAffected > 0)
{
return true;
}
}
}
return false;
}
///
/// 检查数据库是否存在
///
///
///
///
public static bool DatabaseExists(string connectionString, string databaseName)
{
string query = "SELECT database_id FROM sys.databases WHERE name = @databaseName";
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
using (SqlCommand command = new SqlCommand(query, connection))
{
command.Parameters.AddWithValue("@databaseName", databaseName);
var result = command.ExecuteScalar();
return result != null;
}
}
}
///
/// 创建数据库(需要master权限)
///
///
///
///
///
public static bool CreateDatabase(string connectionString, string databaseName)
{
if (string.IsNullOrEmpty(connectionString))
connectionString = ConnectionString;
if (!connectionString.Contains("master"))
return false;
try
{
string createQuery = $@"CREATE DATABASE {databaseName}";
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
using (SqlCommand command = new SqlCommand(createQuery, connection))
{
command.ExecuteNonQuery();
}
}
return true;
}
catch { return false; }
}
///
/// 删除数据库(需要master权限)
///
/// 表名
///
/// 值存在True
public static bool DeleteDatabase(string databaseName, string connectionString)
{
if (string.IsNullOrEmpty(connectionString))
connectionString = ConnectionString;
if (!connectionString.Contains("master"))
return false;
// 设置 SQL DROP DATABASE 语句
string dropDatabaseQuery = $"DROP DATABASE IF EXISTS {databaseName}";
using (SqlConnection connection = new SqlConnection(connectionString))
{
try
{
// 打开数据库连接
connection.Open();
// 1. 设置数据库为单用户模式,强制断开所有连接
string setSingleUserQuery = $@"ALTER DATABASE [{databaseName}] SET SINGLE_USER WITH ROLLBACK IMMEDIATE;";
using (var cmd = new SqlCommand(setSingleUserQuery, connection))
{
cmd.ExecuteNonQuery();
Debug.WriteLine($"Database {databaseName} is now in single-user mode.");
}
// 创建 MySqlCommand 对象
using (SqlCommand cmd = new SqlCommand(dropDatabaseQuery, connection))
{
// 执行删除数据库操作
cmd.ExecuteNonQuery();
Debug.WriteLine("Database dropped successfully.");
return true;
}
}
catch (Exception ex)
{
Debug.WriteLine("Error: " + ex.Message);
return false;
}
}
}
///
/// 复制表结构和数据(需要master权限)
///
///
///
///
public static bool CopyDatabaseData(string connectionString, string sourceDatabase, string targetDatabase)
{
if (string.IsNullOrEmpty(connectionString))
connectionString = ConnectionString;
if (!connectionString.Contains("master"))
return false;
try
{
using (var connection = new SqlConnection(connectionString))
{
connection.Open();
string useSourceDb = $"USE {sourceDatabase};";
string useTargetDb = $"USE {targetDatabase};";
// 切换到源数据库
using (var cmd = new SqlCommand(useSourceDb, connection))
{
cmd.ExecuteNonQuery();
}
// 获取源数据库中所有表的列表
string getTablesQuery = "SELECT name FROM sys.tables;";
using (var cmd = new SqlCommand(getTablesQuery, connection))
{
// 使用 CommandBehavior.CloseConnection 自动关闭连接
using (var reader = cmd.ExecuteReader(CommandBehavior.CloseConnection))
{
while (reader.Read())
{
string tableName = reader.GetString(0);
Debug.WriteLine($"复制表: {tableName}");
// 复制表结构
string createTableQuery = $"SELECT * INTO {targetDatabase}.dbo.{tableName} FROM {sourceDatabase}.dbo.{tableName} WHERE 1 = 0;";
using (var cmdCreateTable = new SqlCommand(createTableQuery, connection))
{
cmdCreateTable.ExecuteNonQuery();
}
// 复制表数据
string insertDataQuery = $"INSERT INTO {targetDatabase}.dbo.{tableName} SELECT * FROM {sourceDatabase}.dbo.{tableName};";
using (var cmdInsertData = new SqlCommand(insertDataQuery, connection))
{
cmdInsertData.ExecuteNonQuery();
}
}
}
}
}
return true;
}
catch { return false; }
}
public static List GetUserDatabases()
{
List databases = new List();
string connectionString = "Server=localhost;Database=master;Integrated Security=True;";
using (SqlConnection connection = new SqlConnection(connectionString))
{
try
{
connection.Open();
string query = @"
SELECT name
FROM sys.databases
WHERE database_id > 4 -- 过滤系统数据库
AND name NOT IN ('model','msdb','tempdb','DWConfiguration','DWDiagnostics','DWQueue')
AND source_database_id IS NULL -- 排除数据库快照";
using (SqlCommand command = new SqlCommand(query, connection))
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
databases.Add(reader["name"]?.ToString());
}
}
}
catch (SqlException ex)
{
Debug.WriteLine($"数据库查询失败: {ex.Message}");
}
}
return databases;
}
}
}