C#通过用户控件连接到mysql

嘿Guy我是C#的新手。

我的问题是,是否可以连接到数据库(通过webusercontrol)。

我试图列出值来自数据的位置

喜欢

 

做这个的最好方式是什么 ?

usercontrol? 还是其他方式?

所以基本上,如果你有一个数据库活动,你应该首先从中获取数据。

 private static string connString = "server=127.0.0.1; userid=yourUserHere; password=youPasswordHere; database=yourDatabaseNameHere"; public static DataTable SelectData(MySqlCommand command) { try { DataTable dataTable = new DataTable(); using (MySqlConnection connection = new MySqlConnection()) { connection.ConnectionString = connString; connection.Open(); command.Connection = connection; MySqlDataReader reader = command.ExecuteReader(); dataTable.Load(reader); return dataTable; } } catch (MySqlException e) { Console.Write(e.Message); return null; } } 

然后在上下文中,您需要使用SQL行调用此方法。 您应该始终使用参数化查询来最小化SQL注入的风险等。 您还需要将数据表中的信息转换为列表(如果这就是您想要的)。 像这样:

 public List dataTableToString(DataTable table) { List Labels = new List(); foreach (DataRow row in table.Rows) { //index of row you want returned in the list Labels.Add(row[2].tostring()) } return labels } public List whateverInformationYouWantHere(string labelID,) { MySqlCommand command = new MySqlCommand(); command.CommandText = "SELECT * FROM LABELS WHERE LabelID = @labelID"; command.Parameters.AddWithValue("labelID", labelID); return dataTableToString(Databasehandler.SelectData(command)); } 

然后,您所要做的就是制作一个foreach循环并在UL中插入所有标签项。 (如果您有任何疑问,请随时提出)。

看看这个:

HTML:

   

代码背后:

 protected void Page_Load(object sender, EventArgs e) { sample1.InnerText = "just imagine that this text is came from the first column from your DB"; }