c#写一个数据库连接封装
时间: 2024-02-05 07:05:05 浏览: 77
C#连接数据库封装类.doc
以下是一个简单的数据库连接封装的示例代码,使用了C#中的ADO.NET:
```csharp
using System;
using System.Data;
using System.Data.SqlClient;
namespace DatabaseConnection
{
public class DatabaseConnector
{
private string connectionString;
private SqlConnection connection;
public DatabaseConnector(string connectionString)
{
this.connectionString = connectionString;
this.connection = new SqlConnection(connectionString);
}
public void OpenConnection()
{
if (connection.State != ConnectionState.Open)
{
connection.Open();
}
}
public void CloseConnection()
{
if (connection.State != ConnectionState.Closed)
{
connection.Close();
}
}
public DataTable ExecuteQuery(string query)
{
DataTable dataTable = new DataTable();
try
{
OpenConnection();
SqlCommand command = new SqlCommand(query, connection);
SqlDataAdapter adapter = new SqlDataAdapter(command);
adapter.Fill(dataTable);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
CloseConnection();
}
return dataTable;
}
public void ExecuteNonQuery(string query)
{
try
{
OpenConnection();
SqlCommand command = new SqlCommand(query, connection);
command.ExecuteNonQuery();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
CloseConnection();
}
}
}
}
```
使用方法:
```csharp
string connectionString = "Data Source=.;Initial Catalog=MyDatabase;Integrated Security=True";
DatabaseConnector connector = new DatabaseConnector(connectionString);
// 查询
string query = "SELECT * FROM MyTable";
DataTable dataTable = connector.ExecuteQuery(query);
foreach (DataRow row in dataTable.Rows)
{
Console.WriteLine(row["ColumnName"]);
}
// 非查询操作
string insertQuery = "INSERT INTO MyTable (ColumnName) VALUES ('Value')";
connector.ExecuteNonQuery(insertQuery);
```
阅读全文