为什么我得到,“;找不到表0”;

本文关键字:找不到 为什么 | 更新日期: 2023-09-27 18:26:11

在程序启动时,如果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);

而且,我仍然看到消息"即将创建hhs_settings",尽管据推测,createtable 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改为:时,它起了作用(现在有效)

字符串sqlddl="创建表hhs_settings(setting_id int identity(1,1)主键,setting_name nvarchar(40)不为null,setting_value nvarchal(63)不为null)";

为什么我得到,“;找不到表0”;

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,效果会更好

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