gpt4 book ai didi

c# - 如何建立数据库(sql)连接以使用c#从文本字段接收数据?

转载 作者:搜寻专家 更新时间:2023-10-30 22:15:20 24 4
gpt4 key购买 nike

我想建立数据库连接以从文本字段接收数据并将该数据存储在数据库记录中。为此,到目前为止我已经尝试过:

我已经创建了 .mdf 数据库文件,并且我已经创建了名称为 Table1 的表,并且我已经放置了两个文本字段和提交按钮,以及以下代码:data.aspx

<b>Username:<asp:TextBox ID="TextBox1" runat="server" BackColor="AliceBlue">
</asp:TextBox><br/>
<b>Lastname:<asp:TextBox ID="TextBox2" runat="server" BackColor="AliceBlue">
</asp:TextBox><br/>
<asp:Button ID="Button1" runat="server" Text="Submit" OnClick="SubmitBtn_Click"/>

代码文件如下:data.aspx.cs

using System.Web.Configuration;
using System.Data.SqlClient;
protected void SubmitBtn_Click(object sender, EventArgs e)
{
string connectionStrings = "Data Source=|SQLEXPRESS;Integrated
Security=True; Connect Timeout=30;User Instance=True;";

using (SqlConnection sqlConnection = new SqlConnection(connectionStrings))
{
string insertStatement = "INSERT INTO Table1(column1,column2)
VALUES (@col1, @col2)";
SqlCommand sqlCommand = new SqlCommand(insertStatement, sqlConnection);
sqlCommand.Parameters.AddWithValue("@col1", TextBox1.Text);
sqlCommand.Parameters.AddWithValue("@col2", TextBox2.Text);
sqlConnection.Open();
sqlCommand.ExecuteNonQuery();
try
{
sqlConnection.Open();
sqlCommand.ExecuteNonQuery();

}
finally
{
sqlConnection.Close();
}
}


}

我还有如下配置文件来建立连接,代码如下:web.config

<?xml version="1.0"?>
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.0" />

</system.web>
</configuration>

但对于该代码,我在单击提交按钮后收到此错误:

A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)

还有异常(exception):

System.Data.SqlClient.SqlException: A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)

谁能帮帮我?

最佳答案

检查您的 sql server 实例是否正在运行。转到开始->SQL Server 配置管理器
并检查您的sql server 实例是否已启动。

或者尝试将您的连接字符串更改为

string connectionStrings = "Data Source=.\SQLEXPRESS;
Initial Catalog=databaseName Integrated Security=True;";

关于c# - 如何建立数据库(sql)连接以使用c#从文本字段接收数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13991803/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com