在C#中选择语句

时间:2010-05-02 19:48:45

标签: c# sql database ms-access join

我的代码中的问题在哪里?

string constr = "Provider=Microsoft.Jet.OLEDB.4.0;"
  + "Data Source=C:\\Users\\Simon\\Desktop\\test5\\test5\\test5\\save.mdb";

OleDbConnection conn = new OleDbConnection(constr);
string sql = "SELECT users.user_name,naziv,obroki_save.datum"
  + "FROM zivila JOIN obroki_save ON zivila.ID=obroki_save.ID_zivila"
  + "JOIN users ON obroki_save.ID_uporabnika=users.ID";
  OleDbCommand cmd = new OleDbCommand(sql, conn);
conn.Open();
OleDbDataReader reader;
reader = cmd.ExecuteReader();

while (reader.Read())
{
    Console.Write(reader.GetString(0).ToString() + " ,");
    Console.Write(reader.GetString(1).ToString() + " ,");
    Console.WriteLine("");
}

reader.Close();
conn.Close();

2 个答案:

答案 0 :(得分:6)

如果在调试器中运行它,您可以看到问题:

SELECT users.user_name, naziv,obroki_save.datumFROM zivila JOIN obroki_save ...
                                             ^^^^

您在SQL中缺少空格。它应该是这样的:

string sql = "SELECT users.user_name,naziv,obroki_save.datum " // << here
+ "FROM zivila JOIN obroki_save ON zivila.ID=obroki_save.ID_zivila " // << here
+ "JOIN users ON obroki_save.ID_uporabnika=users.ID";

答案 1 :(得分:2)

这是Access,所以你需要括号,你需要选择一个JOIN类型。 LEFT和INNER是通常的选择,所以:

SELECT users.user_name,naziv,obroki_save.datum
FROM (zivila 
LEFT JOIN obroki_save ON zivila.ID=obroki_save.ID_zivila)
LEFT JOIN users ON obroki_save.ID_uporabnika=users.ID