我正在尝试create a connection
但是,它始终采用null
。
下面我提一个方法,我是怎么做的:
Program.cs:
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["CreateConnection"].ConnectionString);
App.config:
<configuration>
<connectionStrings>
<add name="CreateConnection" connectionString="data source=MyDatabase;initial catalog=TestDatabase;integrated security=True;MultipleActiveResultSets=True;user id=ABC;password=Admin@123;App=EntityFramework;" providerName="System.Data.EntityClient" />
</connectionStrings>
</configuration>
答案 0 :(得分:3)
我用以下方式。检查这是否有助于MySQL使用
在App.config文件中
<appSettings>
<add key="DBConnectionString"
value="server=localhost;userid=root;database=databasename"/>
</appSettings>
在Program.cs中
public static string m_strMySQLConnectionString;
static MySqlConnection m_mySqlConnection;
static void Main(string[] args)
{
m_strMySQLConnectionString = ConfigurationManager.AppSettings["DBConnectionString"].ToString();
m_mySqlConnection = null;
}
在DB Helper功能
中public string GetValueFromDB(string strQuery)
{
string strData = "";
try
{
if (m_mySqlConnection == null)
OpenDatabase();
if (string.IsNullOrEmpty(strQuery) == true)
return string.Empty;
MySqlCommand cmd = new MySqlCommand(strQuery, m_mySqlConnection);
object objValue = cmd.ExecuteScalar();
if (objValue == null)
{
cmd.Dispose();
return string.Empty;
}
else
{
strData = (string)cmd.ExecuteScalar();
cmd.Dispose();
}
if (strData == null)
return string.Empty;
else
return strData;
}
catch (MySqlException ex)
{
LogException(ex);
return string.Empty;
}
catch (Exception ex)
{
LogException(ex);
return string.Empty;
}
finally
{
CloseDatabase();
}
}