asp.net连接SQLserver和access很方便,直接用自带的SQLdatasource控件就行了,但是连接mysql数据库就要麻烦一些。
先介绍asp.net连接mysql数据库的步骤。
1引用MySql.Data.dll库文件,这个库文件提供了连接mysql数据库的类,不引用不行,具体的自行百度。
2在web.config中配置连接字符串
providerName="MySql.Data.MySqlClient" />
3在后台用代码连接数据库即可
//通过配置文件得到连接字符串
public static string connectionString = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString;
MySqlConnection connection = new MySqlConnection(connectionString);
MySqlCommand cmd = new MySqlCommand(strSQL, connection);
try
{
connection.Open();
MySqlDataReader myReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
return myReader;
}
其实和操作SQLserver步骤差不多的。这样就能够操作mysql数据库了。
接着封装了一个查询方法
///
/// 执行查询语句,返回MySqlDataReader
///
/// 查询语句
/// MySqlDataReader
public static MySqlDataReader ExecuteReader(string strSQL)
{
MySqlConnection connection = new MySqlConnection(connectionString);
MySqlCommand cmd = new MySqlCommand(strSQL, connection);
try
{
connection.Open();
MySqlDataReader myReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
return myReader;
}
catch (MySql.Data.MySqlClient.MySqlException e)
{
throw e;
}
}
返回一个reader,这样查询数据的时候就很方便了。
接着针对数据库中一个表,用类设计一个模型。
比如文章表:
public class Article
{
public string title { get; set; }
public string content { get; set; }
public string sub_image { get; set; }
public string type { get; set; }
}
其次要查询获得很多个文章记录,所以封装了一下方法以便得到一个包含文章对象的list
private void FillArticleList(string v)
{
MySqlDataReader reader = MySqlHelper.ExecuteReader(v);
while (reader.Read())
{
Article article = new Article();
article.title = reader[1].ToString();
article.content = reader[2].ToString();
article.sub_image = reader[3].ToString();
article.type = reader[4].ToString();
//注意此处的list是一个全局变量哟
Article_list.Add(article);
}
reader.Close();
}
直接在pageload的时候调用这个方法就能将查询的数据填充到一个list中了。
然后在页面中引用:
for (int i = 0; i < Article_list.Count; i++)
{
if(i == 3)
{
break;
}
Response.Write("
");Response.Write("
" + Article_list[i].title + "
");Response.Write("
" + Article_list[i].content + "
");Response.Write("
");}
%>
在页面中直接就能引用到页面后台类文件中定义的变量,这样可以动态生成内容。很方便。
好了,今天就讲到这里,喜欢的朋友可以关注一下,后面内容更精彩。