gpt4 book ai didi

c# - 如何验证您是否已连接到 C# 中的 MySQL 数据库?

转载 作者:行者123 更新时间:2023-11-28 23:28:54 25 4
gpt4 key购买 nike

我在 C# 中添加了对 MySQL 服务器的引用。我以为我的代码是对的。我知道连接值适合测试。这是我的错误:

{“建立与 SQL Server 的连接时发生了与网络相关或特定于实例的错误。未找到服务器或无法访问服务器。验证实例名称是否正确以及 SQL Server 是否配置为允许远程连接.(提供商:命名管道提供商,错误:40 - 无法打开与 SQL Server 的连接)”

我的 WPF 文本框和按钮:

<TextBox x:Name="textError" HorizontalAlignment="Left" Height="35" Margin="125,39,0,0" TextWrapping="Wrap" Text="If Error this will show it" VerticalAlignment="Top" Width="240"/>
<TextBox x:Name="textUser" HorizontalAlignment="Left" Height="23" Margin="125,118,0,0" TextWrapping="Wrap" Text="Username" VerticalAlignment="Top" Width="120"/>
<TextBox x:Name="textPassword" HorizontalAlignment="Left" Height="23" Margin="125,168,0,0" TextWrapping="Wrap" Text="Password" VerticalAlignment="Top" Width="120"/>

我的 C# 代码:

namespace namespace1
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();

}
private MySqlConnection connection;
private string server;
private string database;
private string uid;
private string password;

private void button_Click(object sender, RoutedEventArgs e)
{
if (textUser.Text != "" & textPassword.Text != "")
{
server = "localhost";
database = "test";
uid = "username";
password = "password";
string connectionString;
connectionString = "SERVER=" + server + ";" + "DATABASE=" + database + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";";
connection = new MySqlConnection(connectionString);
string queryText = @"SELECT Count(*) FROM Table1
WHERE username = @Username AND password = @Password";

using (SqlConnection cn = new SqlConnection(connectionString))
using (SqlCommand cmd = new SqlCommand(queryText, cn))
{
cn.Open();
cmd.Parameters.AddWithValue("@Username", textUser.Text);
cmd.Parameters.AddWithValue("@Password", textPassword.Text);
int result = (int)cmd.ExecuteScalar();
if (result > 0)
MessageBox.Show("Logged In!");
else
MessageBox.Show("User Not Found!");
}
}
}
}
}

最佳答案

访问标题为 Download Connector/Net 的 MySQL 下载页面并继续显而易见的事情。请注意寻找最新的下载,因为它会老化。

使用适当的 MySQL 类

using MySql.Data.MySqlClient;

string connString = @"server=localhost;userid=drew;password=OpenSesame;database=stackoverflow";

.

        long lRet = 0;
using (MySqlConnection lconn = new MySqlConnection(connString))
{
lconn.Open();
using (MySqlCommand cmd = new MySqlCommand())
{
cmd.Connection = lconn;
cmd.CommandText = @"select count(*) as theCount from batchQMetricsToUpdate where status=1";
lRet = (long)cmd.ExecuteScalar();
}
}
return(lRet);

添加引用截图:

enter image description here

关于c# - 如何验证您是否已连接到 C# 中的 MySQL 数据库?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38089702/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com