我在下面的#34; Microsoft .NET Compact Framework"中调整了我的代码。作者:Wigley和Wheelwright:
SqlCeConnection cn = new SqlCeConnection(@"Data Source=\My Documents\Traffic.sdf");
String sSQL= "SELECT CarID, Reg, Location FROM Cars");
SqlCeCommand cmdSelect = new SqlCeCommand(sSQL, cn);
cmdSelect.CommandType = CommandType.Text;
SqlCeDataReader dtr = cmdSelect.ExecuteReader(CommandBehavior.Default); // It's "cmd." instead of "cmdSelect." in the book, but that doesn't compile
while (dtr.Read())
{
ListViewItem item = new ListViewItem(dtr.GetInt32(0).ToString());
item.SubItems.Add(dtr.GetString(1));
item.SubItems.Add(dtr.GetString(2));
listViewCars.Items.Add(item);
}
...所以我的代码是这样的:
private String getDataAsXMLFromTable(String tableName, String siteNum)
{
String strXML;
StringBuilder sbXML = new StringBuilder();
String lineId;
String refNum;
String upcCode;
String desc;
String dept;
String vendorId;
String upcPackSize;
String Id;
String packSize;
String unitCost;
String unitList;
String unitQty;
String newItem;
String paddedSiteNum = Prepad(3, siteNum); // this turns "3" into "003" etc.
String conStr = String.Format(@"Data Source=\My Documents\HHSDB{0}.sdf", paddedSiteNum);
MessageBox.Show(String.Format("conStr is {0}", conStr));
SqlCeConnection cn = new SqlCeConnection(conStr);
String qry = String.Format("SELECT * FROM {0}", tableName);
MessageBox.Show(String.Format("qry is {0}", qry));
SqlCeCommand cmdSelect = new SqlCeCommand(qry, cn);
MessageBox.Show("Made it to pt 1"); // <= I see this
cmdSelect.CommandType = CommandType.Text;
SqlCeDataReader dtr = cmdSelect.ExecuteReader(CommandBehavior.Default);
MessageBox.Show("Made it to pt 2"); // <= I don't see this
try
{
while (dtr.Read())
{
lineId = dtr["line_id"].ToString(); // Wiggly uses dtr.GetString(1); would then
have to use GetX()...
refNum = dtr["ref_no"].ToString();
upcCode = dtr["upc_code"].ToString();
desc = dtr["description"].ToString();
dept = dtr["department"].ToString();
vendorId = dtr["vendor_id"].ToString();
upcPackSize = dtr["upc_pack_size"].ToString();
Id = dtr["id"].ToString();
packSize = dtr["pack_size"].ToString();
unitCost = dtr["unit_cost"].ToString();
unitList = dtr["unit_list"].ToString();
unitQty = dtr["unit_qty"].ToString();
newItem = dtr["new_item"].ToString();
strXML = String.Format("<INV><line_id>{0}</line_id><ref_no>{1}</ref_no><upc_code>
{2}</upc_code><description>{3}</description><department>{4}</department><vendor_id>{5}
</vendor_id><upc_pack_size>{6}</upc_pack_size><id>{7}</id><pack_size>{8}</pack_size><unit_cost>{9}
</unit_cost><unit_list>{10}</unit_list><unit_qty>{11}</unit_qty><new_item>{12}</new_item></INV>",
lineId, refNum, upcCode, desc, dept, vendorId, upcPackSize, Id, packSize,
unitCost, unitList, unitQty, newItem);
sbXML.Append(strXML);
}
}
catch (Exception ex)
{
SSCS.ExceptionHandler(ex, "frmCentral.getDataAsXMLFromTable()");
}
return String.Format("<Command>{0}</Command>", sbXML.ToString());
}
我尝试访问的数据库位于手持设备的“我的文档”文件夹中,并命名为&#34; HHSDB003.sdf&#34;
我的第一个MessageBox.Show()显示了这个:
......这确实是数据库所在的位置:
我的第二个MessageBox.Show()显示了这个:
......还有这样一张桌子:
我看到&#34;做到了第1&#34;但不是&#34;把它转到pt 2&#34;,所以它必须在调用ExecuteReader()时失败 - 但为什么呢?
这是我看到的错误消息:
我将NETCFv35.Messages.EN.wm.cab复制到手持设备上.exe所在的文件夹,但它仍然显示与上面相同的错误消息。我是否需要将其放在别处或安装它/以某种方式设置它?点击它并没有做任何事情,只是向我展示了里面的文件。
compactf SqlCeCommand ExecuteReader SqlCeConnection SqlCeDataReader windowsce c#
根据我读到的here,我将路径/文件名放在单引号中,如下所示:
String conStr = String.Format(@"Data Source='\My Documents\HHSDB{0}.sdf'", paddedSiteNum);
......但它没有任何差异。
我根据答案改变了我的代码:
try
{
. . .
string connStr = "Data Source=\"\\My Documents\\HHSDB003.SDF\"";
MessageBox.Show(String.Format("connStr is {0}", connStr));
try
{
SqlCeConnection conn = new SqlCeConnection(connStr);
String qry = String.Format("SELECT * FROM {0}", tableName);
MessageBox.Show(String.Format("qry is {0}", qry));
SqlCeCommand cmdSelect = new SqlCeCommand(qry, conn);
MessageBox.Show("Made it to pt 1"); // <= I see this
cmdSelect.CommandType = CommandType.Text;
conn.Open(); // <= I was missing this
MessageBox.Show("Made it to pt 2"); // <= I don't see this
SqlCeDataReader dtr = cmdSelect.ExecuteReader(CommandBehavior.Default);
. . .
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
...但是在看到&#34之后我得到了一个例外;将它变为第1和第34页 - 我从未见过&#34;做到了第2&#34;
catch块显示的异常消息不显示任何/空字符串。
在掌上电脑的My Documents文件夹中有一个名为HHSDB003.SDF的数据库,它包含一个名为〜的表;那么我在这里失踪了什么呢?
我将catch块更改为:
catch (Exception ex)
{
MessageBox.Show(String.Format("inner ex is {0}", ex.InnerException.ToString()));
}
...现在看到Null Reference Exception作为内部异常。 ???
因为我看到&#34;使它成为pt 1&#34;这里:
string connStr = "Data Source=\"\\My Documents\\HHSDB003.SDF\"";
String qry = String.Format("SELECT * FROM {0}", tableName);
MessageBox.Show(String.Format("connStr is {0}", connStr));
try
{
SqlCeConnection conn = new SqlCeConnection(connStr);
SqlCeCommand cmdSelect = new SqlCeCommand(qry, conn);
MessageBox.Show("Made it to pt 1"); // <= I see this
cmdSelect.CommandType = CommandType.Text;
conn.Open(); // <= I was missing this
...... conn和qry一定很好;那么为什么在conn上打开会导致NRE?
我给这段代码看了一下,看看SqlCeConnection的数据库和数据源属性的val:
MessageBox.Show(
String.Format("db is {0}; data source is {1}", conn.Database, conn.DataSource));
// This should be redundant, but getting an NRE on the Open call...
conn.ConnectionString = connStr;
......我明白了:
db is \My Documents\HHSDB003.SDF
data source is \My Documents\HHSDB003.SDF
数据库和数据源真的应该是一回事吗?
我可能有一个&#34;直播&#34; (全球)与其他地方/以前建立的数据库的连接;这会导致第二次连接崩溃吗?
我知道[,]这是糟糕的设计,但是&#34;它就是它的本质&#34;现在
我从来没有超过打开的电话 - 它的爆炸比乔治布雷特在他的蝙蝠上抓住松焦油更热。这是代码的相关部分:
string connStr = String.Format("Data Source=\"\\My Documents\\HHSDB{0}.SDF\"", paddedSiteNum);
String qry = String.Format("SELECT * FROM {0}", tableName);
MessageBox.Show(String.Format("connstr is {0}; qry is {1}", connStr, qry));
SqlCeConnection conn;
SqlCeCommand cmdSelect;
try
{
conn = new SqlCeConnection(connStr);
cmdSelect = new SqlCeCommand(qry, conn);
cmdSelect.CommandType = CommandType.Text;
MessageBox.Show(
String.Format("db is {0}; data source is {1}, conn string is {2}", conn.Database, conn.DataSource, conn.ConnectionString));
conn.ConnectionString = connStr;
MessageBox.Show("Made it just before conn.Open()"); // <= I always see this
if ((null != conn) && (!conn.State.Equals(ConnectionState.Open)))
{
MessageBox.Show("Will try to Open");
conn.Open();
}
MessageBox.Show("Made it just after conn.Open()"); // <= I never see this; the NRE steals the show
显示的消息框(在&#34;在conn.Open()&#34;之前制作的消息框)是:
然后我看到&#34;将尝试打开&#34;,然后是NRE。
下面,不仅是代码本身,还有调用它的代码。这可能是代码重入问题吗? SendInventoryData()中的第二个foreach循环是否可以调用getDataAsXMLFromTable(),而之前对getDataAsXMLFromTable()的调用尚未完成? 似乎并非如此,因为我永远不会看到&#34;在conn.Open()&#34; - 从来没有。似乎这就是问题,我至少会看一次......
private void mnuSendINV_Click(object sender, EventArgs e)
{
// TODO: Remove after testing; "hijacking" this to query and send the file directly
SendInventoryData();
return;
private void SendInventoryData()
{
String siteNum = String.Empty;
ArrayList sbInventories = new ArrayList();
foreach (String tbl in listboxWork.Items)
{
// Ignore DSD tables; just get INV tables
if (tbl.IndexOf("DSD") >-1) continue;
String tblName = getTableNameForInventoryName(tbl);
siteNum = getSiteNumberFromInventoryName(tbl);
sbInventories.Add(tblName);
}
foreach (string tbl in sbInventories)
{
string strData = getDataAsXMLFromTable(tbl, "003");
string fileName = getINVFileName(siteNum);
String uri = String.Format("http://192.168.125.50:21608/api/inventory/sendXML/duckbill/platypus/{0}", fileName);
RESTfulMethods rm = new RESTfulMethods();
rm.CreateRequestNoCredentials(uri, RESTfulMethods.HttpMethods.POST, strData, "application/xml");
}
}
private String getDataAsXMLFromTable(String tableName, String siteNum)
{
string xmlOutput = String.Empty;
// data/xml fields
String lineId;
String refNum;
. . .
String newItem;
String paddedSiteNum = Prepad(3, siteNum);
string connStr = String.Format("Data Source=\"\\My Documents\\HHSDB{0}.SDF\"", paddedSiteNum);
String qry = String.Format("SELECT * FROM {0}", tableName);
MessageBox.Show(String.Format("connstr is {0}; qry is {1}", connStr, qry));
SqlCeConnection sqlceConn;
SqlCeCommand sqlceCmd;
try
{
sqlceConn = new SqlCeConnection(connStr);
sqlceCmd = new SqlCeCommand(qry, sqlceConn);
sqlceCmd.CommandType = CommandType.Text;
MessageBox.Show("Made it just before conn.Open()"); // <= I see this
if ((null != sqlceConn) && (!sqlceConn.State.Equals(ConnectionState.Open)))
{
MessageBox.Show("Will try to Open"); // <= I see this
sqlceConn.Open();
}
MessageBox.Show("Made it just after conn.Open()"); // <= I don't see this/make it to here; I see the NRE instead
SqlCeDataReader dtr = sqlceCmd.ExecuteReader(CommandBehavior.Default);
XmlDocument doc = new XmlDocument();// Create the XML Declaration, and append it to XML document
XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", null, null);
doc.AppendChild(dec);// Create the root element
XmlElement root = doc.CreateElement("Command");
doc.AppendChild(root);
try
{
while (dtr.Read())
{
// outer INV
XmlElement invRec = doc.CreateElement("INV");
// Line ID
lineId = dtr["line_id"].ToString();
XmlElement _lineId = doc.CreateElement("line_id");
_lineId.InnerText = lineId;
invRec.AppendChild(_lineId);
// Ref Num
refNum = dtr["ref_no"].ToString();
XmlElement _refNum = doc.CreateElement("ref_no");
_refNum.InnerText = refNum;
invRec.AppendChild(_refNum);
. . .
// New Item
newItem = dtr["new_item"].ToString();
XmlElement _new_item = doc.CreateElement("new_item");
_new_item.InnerText = newItem;
invRec.AppendChild(_new_item);
root.AppendChild(invRec);
}
}
finally
{
xmlOutput = doc.OuterXml;
dtr.Close();
if (sqlceCmd.Connection.State == ConnectionState.Open)
{
sqlceCmd.Connection.Close();
}
}
}
catch (Exception ex)
{
MessageBox.Show(String.Format("inner ex is {0}", ex.InnerException.ToString()));
SSCS.ExceptionHandler(ex, "frmCentral.getDataAsXMLFromTable()");
}
return xmlOutput;
} //getDataAsXMLFromTable
注意:使用此代码,我看到:
0) "connstr is Data Source="\My Documents\HHSDB003.SDF"; qry is SELECT * FROM INV12262006091415"
1) "Made it just before conn.open"
2) "Will try to open"
3) "Exception: Null Reference Exception"
INV12262006091415确实存在于HHSDB003.SDF
中我尝试将getDataAsXMLFromTable()包装在一个锁中:
lock (this)
{
. . .
}
那没有帮助;也没有这样做:
public class HHSUtils
{
public static bool InGetDataAsXMLFromTable;
private String getDataAsXMLFromTable(String tableName, String siteNum)
{
if (HHSUtils.InGetDataAsXMLFromTable) return String.Empty;
HHSUtils.InGetDataAsXMLFromTable = true;
. . .
HHSUtils.InGetDataAsXMLFromTable = false;
return xmlOutput;
}
现在为100确认。
答案 0 :(得分:5)
您忘了打开连接。
string connString = "Data Source=\"\\My Documents\\HHSDB003.sdf\"";
string query = "SELECT * FROM MyTable";
SqlCeConnection conn = new SqlCeConnection(connString);
SqlCeCommand cmd = new SqlCeCommand(query, conn);
conn.Open(); // <--- THIS
SqlCeDataReader rdr = cmd.ExecuteReader();
try
{
// Iterate through the results
while (rdr.Read())
{
}
}
finally
{
// Always call Close when done reading
rdr.Close();
// Always call Close when done reading
conn.Close();
}