【问题标题】:C# connect to mysql through user controlC#通过用户控制连接mysql
【发布时间】:2017-09-14 01:10:22
【问题描述】:

大家好,我是 C# 新手。

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

我正在尝试列出值来自数据的位置

喜欢

<div>
    <ul>
        <li><a href="#">This value comes from database tabel</a></li>
        <li><a href="#">This 1 too</a></li>
        <li><a href="#">and this 1 too</a></li>
   </ul>
</div>

最好的方法是什么?

用户控制?还是其他方式?

【问题讨论】:

  • 你让自己变得更复杂了。让自己探索更多关于如何使用 C# 连接数据库的知识。
  • 查看加载事件,然后将数据库调用放在其中。您正在尝试做一些不需要的事情
  • 这是我们作为一个团队必须要做的事情,这就是结果:(我同意这是我必须做的更多工作。
  • 我可以给你一个示例,请稍等

标签: c# mysql


【解决方案1】:

看看这个:

HTML:

 <div>
     <ul>
        <li><a href="#" id="sample1" runat="server">This value comes from database tabel</a></li>
        <li><a href="#">This 1 too</a></li>
        <li><a href="#">and this 1 too</a></li>
        </ul>
    </div>

代码隐藏:

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

【讨论】:

  • 这样做并尝试运行您的项目。
  • 嗯,谢谢你的想法,我要试试 :)
【解决方案2】:

所以基本上,如果您有一个处于活动状态的数据库,您应该首先从中取出数据。

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<string> dataTableToString(DataTable table)
        {
            List<string> Labels = new List<string>();
            foreach (DataRow row in table.Rows)
            {
                //index of row you want returned in the list
                Labels.Add(row[2].tostring())
            }
         return labels
         }
public List<string> 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 中插入所有标签项。 (如果您有任何问题,请随时提出)。

【讨论】:

    猜你喜欢
    • 2012-02-12
    • 2015-12-15
    • 1970-01-01
    • 2012-04-03
    • 2022-11-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多