FROM语句子句出错

时间:2015-08-24 13:32:35

标签: c# sql database

我试图执行此代码,但我的查询中一直出现错误

string str = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\\Main database.accdb;Jet OLEDB:Database Password=123456";            

OleDbConnection con = new OleDbConnection(str);

string query = "SELECT[Total price],[Parameter change] FROM [Firebird m0 Damage]='" + comboBox6.Text + "' ";
OleDbCommand cmd = new OleDbCommand(query, con);

OleDbDataReader dbr;

try
{
    con.Open();

    dbr = cmd.ExecuteReader();

    while(dbr.Read())
    {
           string me = (string) dbr["[Total price]"];
           textBox15.Text = me;
    }
}
catch(Exception es)
{
    MessageBox.Show(es.Message);
}

我尝试执行此查询但也失败了

select * 
from [Total price],[Parameter change] 
where [Firebird m0 Damage]

有什么建议吗?

2 个答案:

答案 0 :(得分:0)

如果格式化您的查询以使其可读(感谢C#中的@""字符串)

string query = 
  @"SELECT [Total price],
           [Parameter change]  
      FROM [Firebird m0 Damage]='" + comboBox6.Text + "'"; 

您会看到FROM 完全错误正如DBMS所说的那样。 也许你想要这样的东西:

string query = 
  @"SELECT [Total price],
           [Parameter change]  
      FROM [Firebird m0] 
     WHERE [Damage] = '" + comboBox6.Text + "'"; // looks that you want "WHERE"

如果是你的情况,你可以写一个更好的参数化 SQL

string query = 
  @"SELECT [Total price],
           [Parameter change]  
      FROM [Firebird m0] 
     WHERE [Damage] = ?"; 

并将comboBox6.Text作为参数传递。

代码将是这样的:

...
// Put IDisposable into using
using (OleDbConnection con = new OleDbConnection(str)) {
  con.Open();

  // Make SQL being readable
  string query = 
    @"SELECT [Total price],
             [Parameter change]  
        FROM [Firebird m0] 
       WHERE [Damage] = ?"; 

  // Put IDisposable into using
  using (OleDbCommand cmd = new OleDbCommand(query, con)) {
    cmd.Parameters.Add(comboBox6.Text);

    // Put IDisposable into using
    using (OleDbDataReader dbr = cmd.ExecuteReader()) {
      if (dbr.Read()) // You don't need "while" just "if"
        textBox15.Text = Convert.ToString(dbr["[Total price]"]);
    }
  }
}

答案 1 :(得分:0)

您的查询中缺少表名和where子句..

string query = "SELECT[Total price],[Parameter change] FROM [TableName] Where [Firebird m0 Damage]='" + comboBox6.Text + "' ";