gpt4 book ai didi

c# - 在 SqlConnection.Open()、asp.net 上未将对象引用设置为对象的实例

转载 作者:行者123 更新时间:2023-11-29 08:23:29 27 4
gpt4 key购买 nike

刚刚使用 C# 学习 asp.net,当我尝试打开与数据库的连接时,我的代码抛出此异常:

string connectionString ="DataSource=localhost,3306;Database=somedatabase;Uid=username;Pwd=password;";
using(SqlConnection con = new SqlConnection(connectionString))
{
con.Open(); // Exception Thrown Here
}

看起来相对简单,所以我真的不知道为什么会发生这种情况。

还有一件事;

所有这些代码都位于网页上的标签内(不太确定这是否有任何区别,对于 ASP.NET 来说相当新)

干杯!

编辑-

嘿,这是剩下的部分。我将研究哈比卜的解决方案。

我缺少一些程序集(mysql),但是当我尝试它时我会回来。

<%@ Language=C# %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<%@ Import Namespace="MySql" %>

<HTML>
<script runat="server" language="C#">
void MyButton_OnClick(Object sender, EventArgs e)
{

}

void Page_Load(Object sender, EventArgs e)
{
// GET THE USERNAME AND PASSWORD FROM THE CLIENT
NameValueCollection nvc = Request.Form;

string username = nvc["username"];
string password = nvc["password"];
Login(username, password);
}

void Login(string username, string password)
{
string connectionString = "Data Source=localhost,3306;Database=something;Uid=somename;Pwd=somepass;";
using(MySqlConnection con = new MySqlConnection(connectionString))
{
con.Open();
/*
if (con.State != ConnectionState.Open)
return;

try
{
SqlDataReader reader = null;
SqlCommand command = new SqlCommand("SELECT * FROM accounts WHERE username=@username AND password=@password", con);

reader = command.ExecuteReader();
Response.Write(reader[0]);
}
catch (Exception e)
{
Response.Write(e.ToString());
}

con.Close();*/
}
}

最佳答案

您正在尝试通过SqlConnection打开MySQL数据库连接,请使用MySql.Data.MySqlClient.MySqlConnection

SqlConnection类用于 SQL Server 连接。

关于c# - 在 SqlConnection.Open()、asp.net 上未将对象引用设置为对象的实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18641972/

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