c# 编写代码实现:判断输入数据是否已经在MySQL表内重复如果不重复就添加进去
您可以使用以下代码来实现判断输入数据是否已经在MySQL表内重复,并将其添加进去:
using MySql.Data.MySqlClient;
public class MySQLHelper
{
private string connectionString = "YourConnectionString"; // 替换为您的MySQL连接字符串
public bool IsDataExists(string inputData)
{
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
connection.Open();
string query = "SELECT COUNT(*) FROM YourTableName WHERE YourColumnName = @InputData";
using (MySqlCommand command = new MySqlCommand(query, connection))
{
command.Parameters.AddWithValue("@InputData", inputData);
int count = Convert.ToInt32(command.ExecuteScalar());
return count > 0;
}
}
}
public void AddData(string inputData)
{
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
connection.Open();
string query = "INSERT INTO YourTableName (YourColumnName) VALUES (@InputData)";
using (MySqlCommand command = new MySqlCommand(query, connection))
{
command.Parameters.AddWithValue("@InputData", inputData);
command.ExecuteNonQuery();
}
}
}
}
请注意将上述代码中的YourConnectionString替换为您的MySQL连接字符串,YourTableName替换为您的表名,YourColumnName替换为您的列名。
使用示例:
MySQLHelper mySQLHelper = new MySQLHelper();
string inputData = "YourInputData"; // 替换为您的输入数据
if (mySQLHelper.IsDataExists(inputData))
{
Console.WriteLine("数据已存在");
}
else
{
mySQLHelper.AddData(inputData);
Console.WriteLine("数据已添加");
}
以上代码会首先判断输入数据是否已存在于MySQL表中,如果存在则输出"数据已存在",如果不存在则将其添加到表中,并输出"数据已添加"。
原文地址: https://www.cveoy.top/t/topic/i9fF 著作权归作者所有。请勿转载和采集!