如何将变量传递到SqlCommand语句中并插入数据库表中 [英] How to pass variable into SqlCommand statement and insert into database table

查看:281
本文介绍了如何将变量传递到SqlCommand语句中并插入数据库表中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用C#编写一个小程序,该程序使用SQL根据用户的输入在运行时将值存储到数据库中.

I'm writing a small program in C# that uses SQL to store values into a database at runtime based on input by the user.

唯一的问题是我无法弄清楚将变量传递到数据库中的正确Sql语法.

The only problem is I can't figure out the correct Sql syntax to pass variables into my database.

private void button1_Click(object sender, EventArgs e)
    {
        int num = 2;

        using (SqlCeConnection c = new SqlCeConnection(
            Properties.Settings.Default.rentalDataConnectionString))
        {
            c.Open();
            string insertString = @"insert into Buildings(name, street, city, state, zip, numUnits) values('name', 'street', 'city', 'state', @num, 332323)";
            SqlCeCommand cmd = new SqlCeCommand(insertString, c);
            cmd.ExecuteNonQuery();
            c.Close();
        }

        this.DialogResult = DialogResult.OK;
    }

在此代码段中,我将使用所有静态值,但要尝试传递给数据库的num变量除外.

In this code snippet I'm using all static values except for the num variable which I'm trying to pass to the database.

在运行时出现此错误:

A parameter is missing. [ Parameter ordinal = 1 ]

谢谢

推荐答案

在执行命令之前,向命令添加参数:

Add a parameter to the command before executing it:

cmd.Parameters.Add("@num", SqlDbType.Int).Value = num;

这篇关于如何将变量传递到SqlCommand语句中并插入数据库表中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆