【发布时间】:2017-02-19 22:04:45
【问题描述】:
寻求一些帮助,将数组值写入我的 sql 数据库中的一张表。 该数组已经计算了所有值,我想将这些值插入到我的数据库中。但是,当我运行代码时,我收到一条错误消息,指出“MySql.Data.dll 中发生了 'MySql.Data.MySqlClient.MySqlException' 类型的未处理异常
附加信息:参数“@PE”已经定义。”
如果我删除它之前的参数,每个参数的含义都是一样的。
我不太确定发生了什么,因为我以另一种形式使用此代码将内容写入数据库并且效果很好!任何帮助都会很棒。
我的代码是,
试试
{
string myconnection = "datasource=localhost;port=3306;username=root;password=1234";
MySqlConnection myconn = new MySqlConnection(myconnection);
MySqlDataAdapter MyDataAdaptor = new MySqlDataAdapter();
MyDataAdaptor.SelectCommand = new MySqlCommand("select * lossdatabase.forecasttable;", myconn);
MySqlCommandBuilder cb = new MySqlCommandBuilder(MyDataAdaptor);
myconn.Open();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
string constring = "datasource=localhost;port=3306;username=root;password=1234; ";
string query = " insert into lossdatabase.forecasttable (PE, Production_Time, Potential) VALUES(@PE, @Production_Time, @Potential;";
MySqlConnection conLossDB = new MySqlConnection(constring);
MySqlCommand cmdLossDB = new MySqlCommand(query, conLossDB);
for (int i=0; i<366; i++)
{
cmdLossDB.Parameters.AddWithValue("@PE", textBox2.Text);
cmdLossDB.Parameters.AddWithValue("@Production_Time", forecast[i,2]);
cmdLossDB.Parameters.AddWithValue("@Potential", forecast[i,3]);
}
MySqlDataReader myReader;
try
{
conLossDB.Open();
myReader = cmdLossDB.ExecuteReader();
MessageBox.Show("Forecast Results Saved");
while (myReader.Read())
{
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
【问题讨论】:
-
select * FROM lossdatabase.forecasttable;你忘了你的 FROM 了。 -
并且您的插入查询末尾也缺少
)。 -
您需要将“MySqlCommand cmdLossDB = ...”行移动到循环中,并在循环中执行您的查询。
-
创建一个mysql准备好的语句并像这里一样添加批处理:stackoverflow.com/questions/4355046/…
标签: c# mysql sql arrays database