我正在尝试制作一个程序时出现问题,这是为了检查一个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();
}
}
}
}
答案 0 :(得分:1)
您在插入声明中缺少电子邮件。它应该是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...");
}
答案 1 :(得分:1)
我认为您在将详细信息保存到数据库时使用的是cmd而不是cmd2。 :)
答案 2 :(得分:0)
另外,您可以在代码中使用简短版本;)
string query = "SELECT COUNT(*) FROM UserInfo WHERE Username='" + txtUsername.Text + "'";
MySqlCommand cmd = new MySqlCommand(query, connection);
if (cmd.ExecuteScalar()>0)
{
MessageBox.Show("User Already Exits", "Oswald", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
query = "INSERT INTO UserInfo (Username, ...
或者您可能为UserInfo添加唯一索引。