提问人:jan411 提问时间:3/19/2022 更新时间:3/19/2022 访问量:664
创建新的 MysqlConnection 时 Asp.net System.NullReferenceException
Asp.net System.NullReferenceException when creating new MysqlConnection
问:
'我是 asp.net 的新手,当我尝试连接到MySQL数据库时,我遇到了这个错误。错误信息
这是我在 web.config 文件中的代码
<configuration>
<appSettings>
<add key="HostPrefix" value="/root" />
<add key="ServerIp" value="localhost" />
<add key="MysqlConnectionstring" value="server=localhost;Database=world;port=3306;user=root;password=1234;SslMode=none" />
<add key="UserImagePath" value="world\city\" />
</appSettings>
这是我的数据库连接代码
using Common;
using MySql.Data.MySqlClient;
using System;
using System.Data;
using System.Data.SqlClient;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Configuration;
namespace Repositories
{
public class StudentRepository
{
private string ConnectionstringMaster = WebConfigurationManager.AppSettings["MysqlConnectionString"];
private static readonly NLog.Logger Logger = NLog.LogManager.GetCurrentClassLogger();
public studentsModel UserRegistration(string Id )
{ studentsModel stud1 = new studentsModel();
try
{
string Query = "select ID,Name,CountryCode,District from world.city where ID='" + Id + "'";
using (var connection = new MySqlConnection(ConnectionstringMaster))
{
using (var command= new MySqlCommand(Query,connection))
{
connection.Open();
using (var sdr=command.ExecuteReader())
{
while (sdr.Read())
{
stud1.FirstName = sdr["Name"].ToString();
}
}
}
}
return stud1;
}
catch (Exception e)
{
Logger.Info("inside Exception Repo Userregistration "+e.ToString());
return stud1;
}
}
}
}
在这里,我尝试从数据库中获取数据并将这些值分配给 studentmodel stud1 。但是当我尝试在localhost中与我的数据库创建新的MySQL连接时 它给出了这样的例外。
ispasswordExpired:connection.ispasswordExpired 引发了类型为“System.nullReferenceException”的异常
ServerThread :连接。ServerThread 引发了类型为“System.nullReferenceException”的异常
ServerVersion :连接。ServerVersion 引发了“System.nullReferenceException”类型的异常
答:
0赞
Tu deschizi eu inchid
3/19/2022
#1
您需要向 Web.Config 添加 a。connectionStrings
Web.config:
<configuration>
<connectionStrings>
<add name="MysqlConnectionstring" connectionString="Server=myServerName;Port=3306;Database=myDatabaseName;Uid=testUser;Pwd=myPassword;" />
</connectionStrings>
...
</configuration>
0赞
Rahul Sharma
3/19/2022
#2
首先需要在文件中添加 connectionStrings 部分,并将其从该部分中删除,如下所示:web.config
appSettings
<configuration>
<connectionStrings>
<add name="MysqlConnectionstring" connectionString="server=localhost;Database=world;port=3306;user=root;password=1234;SslMode=none" />
</connectionStrings>
<appSettings>
<add key="HostPrefix" value="/root" />
<add key="ServerIp" value="localhost" />
<add key="" value="" />
<add key="UserImagePath" value="world\city\" />
</appSettings>
</configuration>
然后,可以通过访问代码中的属性来访问连接字符串值,如下所示:ConnectionString
private string ConnectionstringMaster = ConfigurationManager.ConnectionStrings["MysqlConnectionstring"].ConnectionString;
评论