简体   繁体   English

如何使用数据库中的值填充数据表

[英]how can I populate data table with values from a database

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. 我想使用Select条件和从文本框中获取的值。我在C#中编写了以下代码,请告诉我这是否是正确的方法。 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)
{
}

Problem is in your below code line for GetDataTable (string sql) method. 问题出在GetDataTable (string sql)方法的下面的代码行中。 You will have to use ConnectionString property. 您将不得不使用ConnectionString属性。 I would suggest you to read about ADO.NET more from MSDN. 我建议你从MSDN上阅读更多关于ADO.NET内容。

using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ToString()))
        {

Should be 应该

ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString

It should look like 应该是这样的

using (SqlConnection conn = new 
SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
        {
public static class SqlDBHelper
{
    public static DataSet ExecuteDataSet(string sql, CommandType cmdType, params SqlParameter[] parameters)
    {
        using (DataSet ds = new DataSet())
        using (SqlConnection connStr = new SqlConnection(ConfigurationManager.ConnectionStrings["DbConn"].ConnectionString))
        using (SqlCommand cmd = new SqlCommand(sql, connStr))
        {
            cmd.CommandType = cmdType;
            foreach (var item in parameters)
            {
                cmd.Parameters.Add(item);
            }

            try
            {
                cmd.Connection.Open();
                new SqlDataAdapter(cmd).Fill(ds);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return ds;
        }
    }
}

your code looks right except the connection string. 您的代码看起来正确,连接字符串除外。 You have declared the connection string at the beginning as 您已在开头声明了连接字符串

  SqlConnection conn = new SqlConnection(@"Data      Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\rdb.mdf;Integrated Security=True;User Instance=True");

But in your connection initialization it looks like you are getting it from App config file. 但在您的连接初始化中,它看起来就像是从App配置文件中获取它。

using (SqlConnection conn = new  SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ToString()))

So instead of having connection in your code put it in the app config file and remove the connection from your code something like this 因此,不要在代码中建立连接,而是将其放在app配置文件中,并从代码中删除这样的连接

     <?xml version="1.0"?>
<configuration>
  <connectionStrings>
    <add name="ConnectionString" 
    connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\rdb.mdf;Integrated Security=True;User Instance=True"/>
  </connectionStrings>
</configuration> 

Thank you, 谢谢,

Birhanu Birhanu

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用SQL Server数据库中的值填充列表? - How can I populate a list with values from a SQL Server database? 如何使用 combobox 中的数据库值填充文本框? - How can I populate a textbox with database values from a combobox? 如何使用 Ajax 从数据库值加载或填充表? - How to load or populate the table from database values using Ajax? 如何根据 C# 中数据库中的数据表值在 Winforms 中生成动态按钮? - How Can I Generate Dynamic Buttons in Winforms based on the data table values from Database in C#? 如何使用数据库中的值填充CheckBoxList? - How do I populate my CheckBoxList with values from my database? 如何使用访问数据库中的数据填充组合框并使用其筛选数据网格? - How can i populate a combo box with data from an access database and use it to filter a datagrid? 如何在LINQ中填充数据。从字符串的每个字符的值中选择? - How can I populate data inside a LINQ .Select from the values of each character of a string? 如何将大容量数据从数据库表填充到组合框? -C#.NET - How Can i Populate Bulk of Data from a DB Table into a Combo Box? - C#.NET 如何将数据从数据表直接添加到数据库表? - How can I add data from DataTable to database table directly? 如何使用数据库中的数据填充下拉列表 - How to populate dropdown list with data from database
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM