You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#传递整数变量到SQL语句报错:未声明标量变量@booking_id

解决SQL参数未声明及查询语法错误的问题

我一眼就看到了两个关键问题导致你的代码报错,咱们一步步来修复:

1. SQL查询语句的语法错误

你的JOIN子句写法完全不对,还存在表名拼写错误:

  • 数据库里的服务表是Services,你写了Service,表名不匹配
  • 预订表是Booking,你写成了Bookings,同样和数据库表名不符
  • JOIN的正确语法是INNER JOIN 目标表 ON 关联字段相等,你之前的INNER JOIN Service.service_id ON BoughtServices.service_id属于语法错误

修正后的SQL语句应该是:

SELECT Services.name, Services.price, BoughtServices.amount 
FROM BoughtServices
INNER JOIN Services ON Services.service_id = BoughtServices.service_id
INNER JOIN Booking ON Booking.booking_id = BoughtServices.booking_id
WHERE Booking.booking_id = @booking_id

我调整了表的关联顺序,从中间表BoughtServices开始关联,逻辑会更清晰。

2. SqlDataAdapter未绑定带参数的SqlCommand

你明明创建了带参数的SqlCommand对象,但初始化SqlDataAdapter的时候却用了原始的query字符串,导致参数根本没被传递到查询里——这就是报错说@booking_id未声明的核心原因。

正确的做法是用已经添加好参数的SqlCommand来初始化SqlDataAdapter,而不是直接用字符串。

修正后的Form2完整代码

private void Form2_Load(object sender, EventArgs e) {
    // 替换成你的实际SQL连接字符串
    string connectionString = "你的数据库连接字符串";
    
    using(SqlConnection connection = new SqlConnection(connectionString)) {
        // 修正后的SQL查询语句
        string query = "SELECT Services.name, Services.price, BoughtServices.amount " +
                       "FROM BoughtServices " +
                       "INNER JOIN Services ON Services.service_id = BoughtServices.service_id " +
                       "INNER JOIN Booking ON Booking.booking_id = BoughtServices.booking_id " +
                       "WHERE Booking.booking_id = @booking_id";
        
        // 创建SqlCommand并绑定参数
        SqlCommand command = new SqlCommand(query, connection);
        command.Parameters.Add("@booking_id", SqlDbType.Int).Value = Form1.DataToForm2.booking_id;
        
        // 用带参数的SqlCommand初始化SqlDataAdapter(这里是关键修正)
        var dataAdapter = new SqlDataAdapter(command);
        DataSet ds = new DataSet();
        dataAdapter.Fill(ds);
        
        dataGridView1.ReadOnly = true;
        dataGridView2.DataSource = ds.Tables[0];
    }
}

额外的优化建议

你可以把静态类传参改成通过Form2构造函数传值,这样更优雅也避免静态变量的潜在冲突:

// Form2新增构造函数
private int _bookingId;
public Form2(int bookingId) {
    InitializeComponent();
    _bookingId = bookingId;
}

// Form1调用Form2的代码修改
private void button_CreateInvoice_Click(object sender, EventArgs e) {
    int bookingId = Convert.ToInt32(dataGridView1.CurrentRow.Cells[0].Value);
    Form2 f2 = new Form2(bookingId);
    f2.Show();
}

// Form2里使用参数时直接用_bookingId
command.Parameters.Add("@booking_id", SqlDbType.Int).Value = _bookingId;

内容的提问来源于stack exchange,提问作者Jokhe

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 07:15:47