C#-I';我正在尝试创建MS SQL连接(连接字符串位于XML文件中)
XML文件具有MS SQL ConnectionString,并用C#读取该XML。 但这不是工作。 错误消息为“未处理invalidOperationException” 如何解决 1.XML代码C#-I';我正在尝试创建MS SQL连接(连接字符串位于XML文件中),c#,C#,XML文件具有MS SQL ConnectionString,并用C#读取该XML。 但这不是工作。 错误消息为“未处理invalidOperationException” 如何解决 1.XML代码 <?xml version="1.0" encoding="utf-8" ?> <db> <connectionstring>Data Source=BALALOJANAN\\SQLEXPRESS;Initial Catalog=test;Integrated S
<?xml version="1.0" encoding="utf-8" ?>
<db>
<connectionstring>Data Source=BALALOJANAN\\SQLEXPRESS;Initial Catalog=test;Integrated Security=True</connectionstring>
</db>
2.2 XML读取代码(以公共形式)
2.3插入编码(按钮时钟事件)
3.错误消息
来自
连接到SQL Server时,我遇到实例失败
反复试验告诉我问题出在“数据源=。\\SQLEXPRESS;”
是双人房
这是C#中的转义序列。当我将连接字符串切换到。\SQLEXPRESS时,一切正常
您的数据源是data source=BALALOJANAN\\SQLEXPRESS
如下所示
private void button1_Click(object sender, EventArgs e)
{
OleDbConnection conn;
conn = new OleDbConnection(@"Provider=Microsoft.Jet.OleDb.4.0;Data Source=C:\Users\Excel\Desktop\Coding\Microsoft Access\Northwind.mdb");
conn.Open();
OleDbCommand cmd = conn.CreateCommand();
cmd.CommandText = @"INSERT INTO MyExcelTable([Fname], [Lname], [Address])VALUES('" + textBox1.Text + "', '" + textBox2.Text + "','" + textBox3.Text + "')";
cmd.ExecuteNonQuery();
conn.Close();
}
确保以正确的方式使用连接字符串
简单地用调试器进行调试,肯定会告诉您问题出在哪里?我们不需要代码的全部3部分。要么连接字符串错误,要么XML代码读取不正确,要么创建连接的方式错误。并不是全部都是3。通过将错误发布为屏幕截图,您已经成功地阻止了其他有相同错误的人找到这个问题。报告说可能是3中的第一个-您的连接字符串是错误的。
string connectionstring = "";
XmlTextReader re = new XmlTextReader("XMLFile1.xml");
XmlNodeType ty;
while (re.Read())
{
ty = re.NodeType;
if (ty == XmlNodeType.Element)
{
if (re.Name == "connectionstring")
{
re.Read();
connectionstring = re.Value;
}
}
}
SqlConnection sc = new SqlConnection(connectionstring);
sc.Open();
SqlCommand cmd = new SqlCommand("insert into a(id,name)values '" + textBox1.Text + "','" + textBox1.Text + "'", sc);
cmd.ExecuteNonQuery();
MessageBox.Show("Sucess");
sc.Close();
<connectionStrings>
<add name="NorthwindConnString"
connectionString="Data Source=.\\\\SQLEXPRESS;Initial Catalog=Northwind;Integrated Security=True"
providerName="System.Data.SqlClient"/>
</connectionStrings>
private void button1_Click(object sender, EventArgs e)
{
OleDbConnection conn;
conn = new OleDbConnection(@"Provider=Microsoft.Jet.OleDb.4.0;Data Source=C:\Users\Excel\Desktop\Coding\Microsoft Access\Northwind.mdb");
conn.Open();
OleDbCommand cmd = conn.CreateCommand();
cmd.CommandText = @"INSERT INTO MyExcelTable([Fname], [Lname], [Address])VALUES('" + textBox1.Text + "', '" + textBox2.Text + "','" + textBox3.Text + "')";
cmd.ExecuteNonQuery();
conn.Close();
}