c# - C#中如何执行sql select语句

标签 c# sql sql-server database select

我这里有个小问题: 我有一个组合框,它从数据库中的列中获取它的值,我用它来将数据输入回数据库中的另一个位置 喜欢

comboBox2.DataSource = ds1.Tables[0];
comboBox2.DisplayMember = "DoctorName";
comboBox2.ValueMember = "DoctorCode";
comboBox2.BindingContext = this.BindingContext;

这用医生的名字填充组合框,值将是医生的代码 然后

 SqlConnection con = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=c:\users\administrator\documents\visual studio 2010\Projects\Clinic\Clinic\Clinc.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True");
        con.Open();
        SqlCommand cmd1 = new SqlCommand("SELECT   Doctors.DoctorCode, Doctors.DoctorName, SessionReservations.SessionCode, SessionReservations.PatientCode, SessionReservations.ExaminationCode, SessionReservations.DoctorCode AS Expr1, SessionReservations.SessionMonth, SessionReservations.SessionYear   FROM  Doctors INNER JOIN   SessionReservations ON Doctors.DoctorCode = SessionReservations.DoctorCode    WHERE  (Doctors.DoctorCode = @DoctorCode) AND (SessionReservations.SessionMonth = @month) AND (SessionReservations.SessionYear = @year)", con);
        SqlDataAdapter da2 = new SqlDataAdapter(cmd1);
        DataSet ds2 = new DataSet();

        try
        {

            da2.InsertCommand.Parameters.Add("@DoctorCode", SqlDbType.Int).Value = Convert.ToInt32(comboBox2.SelectedValue);
            da2.InsertCommand.Parameters.Add("@month", SqlDbType.Int).Value = comboBox1.SelectedValue;
            da2.InsertCommand.Parameters.Add("@year", SqlDbType.Int).Value = textBox2.Text;

            da2.Fill(ds2);
            cmd1.ExecuteReader();
            con.Close();
}

此代码用于选择特定的行并且选择语句在 sql 管理器中工作正常 但是在运行时会出现错误

"System.NullReferenceException: Object reference not set to an instance of an object. at Clinic.DoctorMoneyCall.button1_Click(Object sender, EventArgs e) in C:\Users\Administrator\documents\visual studio 2010\Projects\Clinic\Clinic\DoctorMoneyCall.cs:line 45"

我只是不明白这是怎么回事

最佳答案

您似乎正在尝试运行选择命令,但您正在将参数添加到插入命令。

        da2.SelectCommand.Parameters.Add("@DoctorCode", SqlDbType.Int).Value = Convert.ToInt32(comboBox2.SelectedValue);
        da2.SelectCommand.Parameters.Add("@month", SqlDbType.Int).Value = comboBox1.SelectedValue;
        da2.SelectCommand.Parameters.Add("@year", SqlDbType.Int).Value = textBox2.Text;

关于c# - C#中如何执行sql select语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13566868/

相关文章:

c# - 是否有扫描执行某些操作的作业表的标准模式?

C# MVC ViewModel 返回 Null - 回传

C# 克隆——使用不可序列化的数据类型

c# - 将 UIImageView 添加到 UIAlertController

SQL Server 账单金额分配

sql-server - 如何在SQL Server数据库中使用 Elasticsearch

c# - Windows Phone 8.1 MapIcon 单击事件

mysql - 如何在mysql中根据行值拆分列?

mysql - 为什么 DISTINCT 使这个查询比没有 DISTINCT 花费的时间长 10 倍?

java - PreparedStatement - 如何指定使用列的默认值