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

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

4

7 回答 7

11
  1. 您对SQL-Injection开放。不要连接字符串来构建您的查询。而是使用 SQL 参数。
  2. 用于using-statement您的连接(以及所有其他实现IDisposable)。Dispose 也会关闭连接,using即使出现错误。
  3. 异常的原因是您没有初始化连接,SqlCommand因为您没有指定连接。您可以使用该属性或适当的构造函数

这是一个例子:

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();
    }
}
于 2012-10-13T18:11:00.203 回答
1

仅仅打开连接是不够的;
您需要concmd.

于 2012-10-13T18:10:35.743 回答
1

Connection与描述的错误完全相同,您尚未设置SQLCommand.

尝试添加:

cmd.Connection = con;

在你打电话之前ExecuteScalar()

于 2012-10-13T18:10:51.113 回答
1

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

cmd.Connection = con;

在执行查询之前。

于 2012-10-13T18:10:58.553 回答
1

您显示的代码存在几个问题 - 尤其是。一些严重的安全问题,我强烈建议您阅读SQL 注入和准备好的语句/参数以及使用.

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

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();
        }
    }
}
于 2012-10-13T18:11:48.957 回答
1

您尚未在 button1_click 中提供连接字符串。

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

您的代码中也有很多错误。它以这种方式工作

{
  // Create Connection Object  
  // Provide connection object with Connection string
  // Create command object
  // Open connection
  // Execute command
  // Close connection
  // Dispose connection
}
于 2012-10-13T18:15:07.493 回答
0
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();
                }
            }

This will be helpful I think and its more safe

于 2018-04-04T14:29:48.287 回答