我只想遍历数据库中的结果。这就是我现在要做的所有事情!这是我尝试调试时遇到的错误:
建立与 SQL Server 的连接时发生与网络相关或特定于实例的错误。服务器未找到或无法访问。验证实例名称是否正确以及 SQL Server 是否配置为允许远程连接。(提供者:SQL 网络接口,错误:26 - 错误定位服务器/指定的实例)
它指向这一行:
// fill dataset into named table
myAdapter.Fill(myDataSet, "Sent");
这是我的整个代码:
// get connection strings from app.config
string conString = ConfigurationManager.ConnectionStrings["Database1ConnectionString"].ConnectionString;
// connection object
SqlConnection myConn = new SqlConnection(conString);
// create adapter
SqlDataAdapter myAdapter = new SqlDataAdapter("select * from `Sent`", myConn);
// create command builder
SqlCommandBuilder myCommandBuilder = new SqlCommandBuilder(myAdapter);
// create dataset
DataSet myDataSet = new DataSet();
// fill dataset into named table
myAdapter.Fill(myDataSet, "Sent");
// query using linq
IEnumerable<DataRow> results
= from row in myDataSet.Tables["Sent"].AsEnumerable()
select row;
// enumerate through results
foreach (DataRow row in results)
{
MessageBox.Show(row.ToString());
}
我能做些什么来解决这个问题?另外,如果有人有更简单的方法在 C# 中使用数据库,我愿意接受你的想法,因为这对我来说很荒谬(在 C# 中操作数据库)。感谢您的帮助。
2012 年 6 月 29 日更新:
以下代码适用于我:
// get connection strings from app.config
string conString = ConfigurationManager.ConnectionStrings["Database1ConnectionString"].ConnectionString;
// connection object
SqlCeConnection myConn = new SqlCeConnection(conString);
// create adapter
SqlCeDataAdapter myAdapter = new SqlCeDataAdapter("select * from [Sent]", myConn);
// create command builder
SqlCeCommandBuilder myCommandBuilder = new SqlCeCommandBuilder(myAdapter);
// create dataset
DataSet myDataSet = new DataSet();
// fill dataset into named table
myAdapter.Fill(myDataSet, "Sent");
// create new row
DataRow newRow = myDataSet.Tables["Sent"].NewRow();
// set field vals
newRow["sendTo"] = sendTo;
newRow["subject"] = subject;
newRow["message"] = message;
// add new row to table
myDataSet.Tables["Sent"].Rows.Add(newRow);
// update database
myAdapter.UpdateCommand = myCommandBuilder.GetUpdateCommand();
int updatedRows = myAdapter.Update(myDataSet, "Sent");
//MessageBox.Show("There were "+updatedRows.ToString()+" updated rows");
// close connection
myConn.Close();