【发布时间】:2016-05-24 18:11:12
【问题描述】:
我想在 SQL server 2014 上的表中插入设备名称和相关序列号的字符串列表。IDE 是 Visual Studio 2015,编程语言是 C#。
当我运行程序并单击button14时,错误是:
参数化查询 '(@ID int,@NAME nvarchar(4000),@RSSI int)INSERT BeaconInfo (ID, N' 需要参数 '@NAME',但未提供。
我不确定我插入 sql 的代码是否正确。
public partial class Form1 : Form
{
int seqnumber = 333;
List<string> items;
string tmp_name;
BluetoothDeviceInfo[] devices;
public Form1()
{
items = new List<string>();
InitializeComponent();
}
private void startScan()
{
listBox1.DataSource = null;
listBox1.Items.Clear();
items.Clear();
Thread bluetoothScanThread = new Thread(new ThreadStart(scan));
bluetoothScanThread.Start();
}
private void scan()
{
updateUI("Starting Scan..");
BluetoothClient client = new BluetoothClient();
devices = client.DiscoverDevicesInRange();
updateUI("Scan complete");
updateUI(devices.Length.ToString() + " devices discovered");
foreach (BluetoothDeviceInfo d in devices)
{
items.Add(d.DeviceName);
}
updateDeviceList();
}
private void button14_Click(object sender, EventArgs e)
{
System.Data.SqlClient.SqlConnection sqlConnection1 = new System.Data.SqlClient.SqlConnection("....");
System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand();
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandText = "INSERT BeaconInfo (ID, Name, RSSI) VALUES (@ID, @NAME, @RSSI)";
cmd.Parameters.AddWithValue("@ID", seqnumber);
cmd.Parameters.AddWithValue("@NAME", tmp_name);
cmd.Parameters.AddWithValue("@RSSI", 55);
cmd.Connection = sqlConnection1;
for (int j = 0; j < items.Count; j++)
{
seqnumber = seqnumber + 1;
tmp_name = items[j];
sqlConnection1.Open();
cmd.ExecuteNonQuery();
sqlConnection1.Close();
}
}
【问题讨论】:
-
tmp_name为空。 Look at this question -
请注意,在循环中更改
tmp_name的值不会更改@NAME参数的值。