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

时间:2015-09-14 17:56:19

标签: c# visual-studio-2008 datatable

我想用数据库中的值填充数据表。我想使用Select条件和从文本框中获取的值。我在C#中编写了以下代码,请告诉我这是否是正确的方法。它显示了关于连接字符串的异常..但我想知道我的方法是否正确..请做评论。

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;
    }
}

4 个答案:

答案 0 :(得分:3)

您的代码出错是因为您没有设置命令的连接属性。

并且对于使用数据表,最简单的方法是使用:

Sitecore.Security.Accounts.User user =     
Sitecore.Security.Authentication.AuthenticationManager.BuildVirtualUser(@"extranet\" + membershipUser.LastName, true);

if (user != null)
{
    string domainRole = @"extranet\externaluser";
    if (Sitecore.Security.Accounts.Role.Exists(domainRole))
    {
        user.Roles.Add(Sitecore.Security.Accounts.Role.FromName(domainRole));
    }

    Sitecore.Security.UserProfile profile = user.Profile;
    profile.FullName = membershipUser.FirstName + " " + membershipUser.LastName;

    bool islogin =  Sitecore.Security.Authentication.AuthenticationManager.LoginVirtualUser(user);
    AuthenticationManager.Login(user.Name,true );
    profile.Save();
}

答案 1 :(得分:0)

问题出现在GetDataTable (string sql)方法的以下代码行中。您必须使用ConnectionString属性。我建议你阅读MSDN上的ADO.NET更多内容。

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

应该是

ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString

应该看起来像

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

答案 2 :(得分:0)

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;
        }
    }
}

答案 3 :(得分:0)

除连接字符串外,您的代码看起来正确。您已将连接字符串声明为

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

但是在您的连接初始化中,它看起来就像是从App配置文件中获取它。

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

因此,不要在代码中建立连接,而是将其放在应用程序配置文件中,并从代码中删除连接 像这样的东西

     <?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> 

谢谢,

Birhanu