如何使用数据库中的值填充数据表 [英] how can I populate data table with values from a database
本文介绍了如何使用数据库中的值填充数据表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想用从数据库中获取的值填充数据表。我想将Select条件与从文本框中获取的值一起使用。我已经在C#中编写了以下代码,请告诉我这是否是正确的方法。它显示有关连接字符串的异常..但我想知道我的方法是否正确..请发表评论。
I wanted to populate data table with the value taken from the database. I want to use Select condition with the values taken from textbox.. I have written the following code in C#, please tell me whether it is a right approach. It is showing exception about connection string.. but I wanted to know whether my approach is correct or not.. please do comment.
public partial class searchsale : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
try
{
SqlConnection conn = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\rdb.mdf;Integrated Security=True;User Instance=True");
conn.Open();
string scriptname = TextBox1.Text;
string accnum = TextBox2.Text;
string sql = @"select scriptname,accnum,Quantity,price from transac where scriptname = @sn, accnum = @an and transactio = 'Sell'";
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = sql;
cmd.Parameters.AddWithValue("@an", accnum);
cmd.Parameters.AddWithValue("@sn", scriptname);
SqlDataReader dr = cmd.ExecuteReader();
DataTable dt = GetDataTable(sql);
}
catch (Exception ex)
{
Response.Write("error" + ex.ToString());
}
}
private DataTable GetDataTable (string sql)
{
DataTable dt = new DataTable();
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ToString()))
{
SqlDataAdapter da = new SqlDataAdapter(sql, conn);
da.Fill(dt);
}
return dt;
}
}
推荐答案
代码错误是因为您尚未设置命令的连接属性。
The error with your code is because you have not set the connection property of your command .
对于使用数据表,最简单的方法是使用:
and for using data table the most simple way is using :
try
{
var connection = @"your connection string";
//your command
var command = "your command";
var dataAdapter = new System.Data.SqlClient.SqlDataAdapter(command, connection);
var dataTable = new DataTable();
//Get data
dataAdapter.Fill(dataTable);
}
catch (System.Data.SqlClient.SqlException sqlEx)
{
//Use sqlEx.Number to hanlde excception more specific
//for example if sqlEx.Number -1 => Could Not Connect to Server.
}
catch (Exception ex)
{
}
这篇关于如何使用数据库中的值填充数据表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文