我有一个简单的Web API应用程序,我想将其连接到主机中的数据库。这是在我的web.config中:
<connectionStrings>
<add name="JarasDB" connectionString="Data Source=localhost;Initial Catalog=JarasDB;Integrated Security=True;" providerName="System.Data.SqlClient" />
</connectionStrings>
我将用以下代码对其进行测试:
public string Get(int id)
{
string connectionString = ConfigurationManager.ConnectionStrings["JarasDB"].ConnectionString;
using (SqlConnection con = new SqlConnection(connectionString))
{
try
{
//
// Open the SqlConnection.
//
con.Open();
//
// The following code uses an SqlCommand based on the SqlConnection.
//
using (SqlCommand command = new SqlCommand("CREATE TABLE Customer(First_Name char(50),Last_Name char(50),Address char(50),City char(50),Country char(25),Birth_Date datetime);", con))
command.ExecuteNonQuery();
}
catch (Exception ex)
{}
}
return strings[id];
}
答案 0 :(得分:1)
发生此问题的原因是您使用SQL Server连接字符串来连接MySQL数据库,该数据库无法正常工作。确保在您的项目中引用了MySQL Connector .NET(即包括MySql.Data.dll
和所有相关程序集),然后从该字符串中替换您的连接字符串:
<!-- Wrong (SQL Server connection string) -->
<add name="JarasDB" connectionString="Data Source=localhost;Initial Catalog=JarasDB;Integrated Security=True;" providerName="System.Data.SqlClient" />
此示例:
<!-- Correct -->
<add name="JarasDB" connectionString="Server=localhost;Port=3306;Database=jarasdb;Uid=UserID;Pwd=XXXXX" providerName="MySql.Data.MySqlClient"/>
另外,有必要使用MySqlConnection
命名空间中的MySqlCommand
和MySql.Data.MySqlClient
来执行DDL查询:
// add this line on top of 'using' lines
using MySql.Data.MySqlClient;
public string Get(int id)
{
string connectionString = ConfigurationManager.ConnectionStrings["JarasDB"].ConnectionString;
using (MySqlConnection con = new MySqlConnection(connectionString))
{
try
{
con.Open();
using (MySqlCommand command = new MySqlCommand("CREATE TABLE Customer(First_Name char(50),Last_Name char(50),Address char(50),City char(50),Country char(25),Birth_Date datetime);", con))
{
command.ExecuteNonQuery();
}
}
catch (Exception ex)
{
// throw exception here
}
}
return strings[id];
}