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);

而且,我仍然看到消息“即将创建 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 更改为:

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

4

2 回答 2

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 会更好

于 2013-08-01T22:27:58.037 回答
1

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

于 2016-03-09T12:58:13.220 回答