在C#中查询数据库信息,通常需要使用ADO.NET技术,以下是使用ADO.NET连接SQL Server数据库并执行查询的示例代码:
using System; using System.Data.SqlClient;
string connectionString = "Server=服务器地址;Database=数据库名称;User Id=用户名;Password=密码;"; using (SqlConnection connection = new SqlConnection(connectionString)) { connection.Open(); // 后续代码... }
三、创建SqlCommand
对象并执行查询
1、简单查询
如果要执行一个简单的SELECT
查询,可以使用以下代码:
string query = "SELECT * FROM TableName"; using (SqlCommand command = new SqlCommand(query, connection)) { using (SqlDataReader reader = command.ExecuteReader()) { while (reader.Read()) { Console.WriteLine(String.Format("Column1={0}, Column2={1}", reader[0], reader[1])); } } }
2、带参数的查询
为了防止SQL注入攻击,建议使用参数化查询:
string queryWithParams = "SELECT * FROM TableName WHERE Column1 = @Param1"; using (SqlCommand commandWithParams = new SqlCommand(queryWithParams, connection)) { commandWithParams.Parameters.AddWithValue("@Param1", "SomeValue"); using (SqlDataReader readerWithParams = commandWithParams.ExecuteReader()) { while (readerWithParams.Read()) { Console.WriteLine(String.Format("Column1={0}, Column2={1}", readerWithParams[0], readerWithParams[1])); } } }
string procName = "StoredProcedureName"; using (SqlCommand procCommand = new SqlCommand(procName, connection)) { procCommand.CommandType = CommandType.StoredProcedure; // 添加存储过程参数(如果有) // procCommand.Parameters.AddWithValue("@ParamName", paramValue); using (SqlDataReader procReader = procCommand.ExecuteReader()) { while (procReader.Read()) { Console.WriteLine(String.Format("Column1={0}, Column2={1}", procReader[0], procReader[1])); } } }
DataTable dataTable = new DataTable(); string selectQuery = "SELECT * FROM TableName"; using (SqlDataAdapter adapter = new SqlDataAdapter(selectQuery, connection)) { adapter.Fill(dataTable); } foreach (DataRow row in dataTable.Rows) { Console.WriteLine(row["Column1"] + ", " + row["Column2"]); }
DataSet dataSet = new DataSet(); string selectQueryForDataset = "SELECT * FROM TableName"; using (SqlDataAdapter datasetAdapter = new SqlDataAdapter(selectQueryForDataset, connection)) { datasetAdapter.Fill(dataSet, "TableName"); } foreach (DataRow datasetRow in dataSet.Tables["TableName"].Rows) { Console.WriteLine(datasetRow["Column1"] + ", " + datasetRow["Column2"]); }
代码示例展示了在C#中使用ADO.NET查询SQL Server数据库信息的多种方法,包括简单查询、带参数的查询、执行存储过程以及使用DataTable
和DataSet
填充数据,开发者可以根据具体需求选择合适的方式来获取和处理数据库中的信息。