如何将SQL查询结果保存在C#.net中的变量中?

如何将SQL查询结果保存在C#.net中的变量中?,c#,sql,C#,Sql,请帮助我解决此错误,我无法将SQL查询结果存储到变量中???仅打开连接是不够的 您需要将con与cmd相关联。这正是所描述的错误,您尚未设置SQLCommand的属性 尝试添加: namespace Hotel { public partial class Billing : Form { SqlConnection con = new SqlConnection(); SqlDataAdapter da; SqlCommand c

请帮助我解决此错误,我无法将SQL查询结果存储到变量中???

仅打开连接是不够的

您需要将
con
cmd
相关联。这正是所描述的错误,您尚未设置
SQLCommand
的属性

尝试添加:

namespace Hotel
{
    public partial class Billing : Form
    {
        SqlConnection con = new SqlConnection();
        SqlDataAdapter da;
        SqlCommand cmd = new SqlCommand();
        DataTable dt = new DataTable();
        public Billing()
        {
            InitializeComponent();
        }

        private void Billing_Load(object sender, EventArgs e)
        {
            con.ConnectionString = "Data Source=.\\SQLEXPRESS;AttachDbFilename=D:\\Projects\\c# assignments\\Hotel Manager\\Hotel\\database\\master.mdf;Integrated Security=True;User Instance=True";
            //loadData();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            con.Open();
            int rno = Int32.Parse(txtRoom.Text);


            cmd.CommandText = "SELECT SUM(ItemRate) FROM logs WHERE RoomNo=" + rno +"";
            int amt = (int)cmd.ExecuteScalar();   //arror is at this part

       //ExecuteScalar: Connection property has not been initialized.

            cmd.CommandText = "INSERT INTO bill VALUES('" + txtBillNo.Text.ToString() + "','" + txtRoom.Text.ToString() + "','" + amt.ToString() + "')";
            con.Close();
            txtBillNo.Text = "";
            txtRoom.Text = "";
            BillView bv = new BillView();
            bv.ShowDialog();
        }
    }
}

在调用
ExecuteScalar()

之前,您已经打开了一个SqlConnection,但还没有告诉SqlCommand对象使用它。尝试添加以下行:

cmd.Connection = con;
在执行查询之前

  • 你是开放的。不要连接字符串以生成查询。而是使用SQL参数
  • 用于连接(以及实现IDisposable的所有其他内容)。Dispose还将关闭连接,即使出现错误,也会使用
    using
  • 出现异常的原因是您没有初始化
    SqlCommand
    的连接,因为您没有指定连接。您可以使用或相应的
  • 下面是一个例子:

    cmd.Connection = con;
    

    您展示的代码存在一些问题,尤其是一些seroius安全问题,我强烈建议您仔细阅读并准备好语句/参数和

    只是一些快速更正/评论:

    int amt;  
    using (var con = new SqlConnection(ConnectionString)) {
        var sql = "SELECT SUM(ItemRate) FROM logs WHERE RoomNo = @RoomNo";
        using (var cmd = new SqlCommand(sql, con)) {
            cmd.Parameters.AddWithValue("@RoomNo", Int32.Parse(txtRoom.Text));
            con.Open();
            amt = (int)cmd.ExecuteScalar();
        }
    }
    

    您尚未在按钮1\u单击中提供连接字符串

    namespace Hotel
    {
        public partial class Billing : Form
        {
            SqlConnection con = new SqlConnection();
            SqlDataAdapter da;
            SqlCommand cmd = new SqlCommand();
            DataTable dt = new DataTable();
            public Billing()
            {
                InitializeComponent();
            }
    
            private void Billing_Load(object sender, EventArgs e)
            {
                con.ConnectionString = "Data Source=.\\SQLEXPRESS;AttachDbFilename=D:\\Projects\\c# assignments\\Hotel Manager\\Hotel\\database\\master.mdf;Integrated Security=True;User Instance=True";
                //loadData();
            }
    
            private void button1_Click(object sender, EventArgs e)
            {
                con.ConnectionString = "Data Source=.\\SQLEXPRESS;AttachDbFilename=D:\\Projects\\c# assignments\\Hotel Manager\\Hotel\\database\\master.mdf;Integrated Security=True;User Instance=True";
                con.Open();
                int rno = Int32.Parse(txtRoom.Text);
    
                cmd.Connection = con; // This solves the problem you see
                // HERE you SHOULD use a SQL paramter instead of appending strings to build your SQL !!!
                cmd.CommandText = "SELECT SUM(ItemRate) FROM logs WHERE RoomNo=" + rno +"";
                int amt = (int)cmd.ExecuteScalar();   //arror is at this part
    
    
                // HERE you SHOULD use a SQL paramter instead of appending strings to build your SQL !!!
                // Another point: you build an INSERT but never execute it ?!?
                cmd.CommandText = "INSERT INTO bill VALUES('" + txtBillNo.Text.ToString() + "','" + txtRoom.Text.ToString() + "','" + amt.ToString() + "')";
                con.Close();
                txtBillNo.Text = "";
                txtRoom.Text = "";
                BillView bv = new BillView();
                bv.ShowDialog();
            }
        }
    }
    
    你的代码中也有很多错误。它是这样工作的

    con.ConnectionString = "Data Source=.\\SQLEXPRESS;AttachDbFilename=D:\\Projects\\c# assignments\\Hotel Manager\\Hotel\\database\\master.mdf;Integrated Security=True;User Instance=True";
    

    我认为这会很有帮助,而且更安全

    当您在按钮事件中使用空con对象时,您正在另一个方法上设置连接字符串。
    {
      // Create Connection Object  
      // Provide connection object with Connection string
      // Create command object
      // Open connection
      // Execute command
      // Close connection
      // Dispose connection
    }
    
    using (SqlConnection sqlcon = new SqlConnection("Connection String HERE"))
            {
                using (SqlCommand sqlcmd= new SqlCommand())
                {
                    sqlcmd.Connection = sqlcon;            
                    sqlcmd.CommandType = CommandType.Text;
                    sqlcmd.CommandText = "SELECT SUM(ItemRate) FROM logs WHERE RoomNo=@rno";
                    slqcmd.Parameters.AddWithValue("@rno", rno);
                    try
                    {
                        sqlcon.Open();
                        command.ExecuteNonQuery();
                    }
                    catch (SqlException)
                    {
                        MessageBox.Show("Your Error Here");
                    }
                    finally
                    {
                        connection.Close();
                    }
                }