我为什么会这样,“找不到表0”?

时间:2013-08-01 22:22:25

标签: c# sql-server-ce compact-framework .net-1.1

在程序启动时,如果它不存在,我正在创建一个SQL Server CE表,并向其添加一条记录:

if (dbconn.isValidTable("hhs_settings") == -1) // <-- (IOW, it's *not* a valid table)
{
    DBUtils.CreateSettingsTable();
    AppSettings.WriteSettingsVal("beltprinter", "None");
}

public static void CreateSettingsTable()
{
    try
    {
        string sqlddl =
            "create table hhs_settings (setting_id int identity (1,1) Primary key,  setting_name varchar(40) not null, setting_value(63) varchar not null)";
        dbconn.DBCommand(sqlddl, false);        
    }
    catch (SqlCeException sqlcex)
    {
        MessageBox.Show("sqlcex - CreateSettingsTable " + sqlcex.Message);
    }
    catch (Exception ex)
    {
        MessageBox.Show("CreateSettingsTable " + ex.Message);
    }
}

...但是当我打开从表中读取的表单时:

lblSelectedPrinter.Text = AppSettings.ReadSettingsVal("beltprinter");

...它失败,“ 找不到表0

public static string ReadSettingsVal(string settingName)
{
    string retVal = string.Empty;
    string sqldml = string.Format("select setting_value from hhs_settings where setting_name = {0}", " + settingName + ");
    // There should only be one value returned, but using the existing getDataSet() method for now...
    DataSet dsSettingVal = frmCentral.dbconn.getDataSet(sqldml);
    foreach (DataRow row in dsSettingVal.Tables[0].Rows)
    {
        if (retVal == string.Empty)
        {
            retVal = row["setting_value"].ToString();
        }
    }
    return retVal;
}

我在这里错过了一步,所以没有创建表(hhs_settings)吗?或... ???

更新

即使更改了所有格式化的字符串,我现在仍然得到相同的错误消息,以便它们现在是:

string sqldml = string.Format("insert into hhs_settings (setting_name, setting_value) values('{0}', '{1}')", settingName, settingVal);
string sqlqry = string.Format("select setting_value from hhs_settings where setting_name = '{0}'", settingName);

并且,我仍然看到msg“即将创建hhs_settings”,尽管可能是可创建的sql已经很好了:

string sqlddl =
    "create table hhs_settings (setting_id int identity (1,1) Primary key,  setting_name varchar(40) not null, setting_value(63) varchar not null)";

...所以,应该创建表(应该使isValidTable()方法返回-1以外的值(当找不到表时它返回的值)。

更新2

当我将ddl更改为:

时,它帮助(现在可以正常工作)

string sqlddl =         “create table hhs_settings(setting_id int identity(1,1)主键,setting_name nvarchar(40)not null,setting_value nvarchar(63)not null)”;

2 个答案:

答案 0 :(得分:2)

string.Format("select setting_value from hhs_settings where setting_name = {0}", " + settingName + ");

结果是

select setting_value from hhs_settings where setting_name =  + settingName + 

显然不是一个正确的SQL。你需要使用这样的东西

string.Format("select setting_value from hhs_settings where setting_name = '{0}'", settingName);

(还要注意参数占位符周围的引号)

但如果您使用参数而不是生成嵌入了所有标识符的SQL

,那就更好了

答案 1 :(得分:1)

如果您使用的是存储过程,请查看其中的传递查询的名称。它应该与前端和后端完全匹配。