gpt4 book ai didi

C# MySql 数据未正确写入/读取

转载 作者:行者123 更新时间:2023-11-29 07:42:54 26 4
gpt4 key购买 nike

我在尝试制作一个程序时遇到了一些麻烦,这是为了检查 mysql 数据库以查看该名称的用户是否已经存在,如果没有,则应该创建一个,并且如果是这样,应该会显示错误提示。

没有编译错误,并且正在到达代码末尾,告诉我“用户已创建”,但没有数据添加到数据库中,不确定我哪里出错了,谢谢!

 using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;
using MySql.Data.MySqlClient;

namespace Oswald
{
public partial class frmRegister : Form
{
public frmRegister()
{
InitializeComponent();
}

private void btnRegister_Click(object sender, EventArgs e)
{
String mysqlConnectionString = "Server=sql3.freesqldatabase.com;Database=sql367701;UID=sql367701;Password=*****;Port=3306";
MySqlConnection connection = new MySqlConnection(mysqlConnectionString);
connection.Open();

string query = "SELECT * FROM UserInfo WHERE Username='" + txtUsername.Text + "'";
bool exists = false;

MySqlCommand cmd = new MySqlCommand(query, connection);
MySqlDataReader reader = cmd.ExecuteReader();

while (reader.Read())
{
if(txtUsername.Text == reader.GetString("Username"))
{
MessageBox.Show("User Already Exits", "Oswald", MessageBoxButtons.OK, MessageBoxIcon.Error);
exists = true;
}
else { exists = false; }
}

reader.Close();

if (exists == false)
{
query = "INSERT INTO UserInfo (Username, Password, Email, IP) VALUES (@username, @password, @ip);";

string ip = new WebClient().DownloadString(@"http://icanhazip.com").Trim();

using (MySqlCommand cmd2 = new MySqlCommand(query, connection))
{
cmd.Parameters.AddWithValue("@username", txtUsername.Text);
cmd.Parameters.AddWithValue("@password", txtPassword.Text);
cmd.Parameters.AddWithValue("@email", txtEmail.Text);
cmd.Parameters.AddWithValue("@ip", ip);
cmd.ExecuteNonQuery();
}

MessageBox.Show("Account Created!", "Oswald", MessageBoxButtons.OK, MessageBoxIcon.Information);
this.Close();
}
}
}
}

最佳答案

您在插入语句中缺少电子邮件。它应该是cmd2。您正在 cmd

上查询
query = "INSERT INTO UserInfo (Username, Password, Email, IP) VALUES (@username, @password, @email, @ip)";
using (MySqlCommand cmd2 = new MySqlCommand(query, connection))
{
cmd2.Parameters.AddWithValue("@username", txtUsername.Text);
cmd2.Parameters.AddWithValue("@password", txtPassword.Text);
cmd2.Parameters.AddWithValue("@email", txtEmail.Text);
cmd2.Parameters.AddWithValue("@ip", ip);
int rows = cmd.ExecuteNonQuery();
if(rows > 0)
MessageBox.Show("insert OK...");
}

关于C# MySql 数据未正确写入/读取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28560161/

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