
服务器
csharpusing System.Data.SqlClient;// Create a new connection to our server.SqlConnection con = new SqlConnection("server=.;Database=cAIpiao;uid=sa;pwd=123");// Create a new SQL command object.SqlCommand com = new SqlCommand("select * from t_LotInfo where Type=@Type and Term=@Term", con);// Add parameters to the command.com.Parameters.Add("@Type", SqlDbType.VarChar).Value = comboBox1.Text;com.Parameters.Add("@Term", SqlDbType.VarChar).Value = textBox1.Text;// Execute the query and get a reader object.using ( SqlDataReader dr = com.ExecuteReader()){ // Create a new DataTable to hold the results. DataTable dt = new DataTable(); // Load the results into the DataTable. dt.Load(dr);}// Close the connection.conn.Close();在上述代码中,我们首先创建了一个新的连接对象,并使用所提供的凭据连接到服务器和数据库。然后,我们为SQL查询创建了一个新的命令对象,并使用参数填充该对象以指定所需的条件。最后,我们执行查询并获取一个数据读取器对象来获取结果。最后,我们关闭了连接。请注意,在上述代码中,我们使用了"dt.Load(dr)"语句来将结果加载到新的 DataTable 中。这是因为在数据库查询完成后,数据读取器对象仍然包含所有获取到的数据。使用此语句可以将这些数据转换为 DataTable 中的行,并在本例中用于填充我们的 Datagridview。另外,请确保你已经正确设置了 Datagridview 的 DataSource 属性以使其与 DataTable 等效。如果需要显示 Datagridview 中的内容,请使用其 DataSource 属性并进行相应设置。希望这能帮助到你!如果还有其他问题,请随时向我提问。Copyright © 2025 IZhiDa.com All Rights Reserved.
知答 版权所有 粤ICP备2023042255号