【发布时间】:2022-12-27 19:17:44
【问题描述】:
I'm right now learning more about C# and SQL connections and doing a challenge their I'm making a simple atm.
This atm will handle create account, check if its exist in database and if not then add to database, if it exist then close the program. Also it will handle rest of the parts an atm does once you have logged in to your card. With take outs and input.
This challenge are just for me to learn more of SQL and C#.
My issue: I'm trying to check if the value exist already in my SQL table but I'm not sure what I'm doing wrong.
Thanks in advance!
bool checkifExist(int number) {
bool itExist;
string queryString;
var cnn = new SqlConnection(connectionString);
DataTable dt = new DataTable();
try
{
cnn.Open();
queryString = "select Count(*) from dbo.User_Card_Information where [CardNumbers] = @cardnumbers";
SqlCommand check_cardnumber = new SqlCommand(queryString, cnn);
check_cardnumber.Parameters.AddWithValue("@cardnumbers", cardnumber);
int cardExist = (int)check_cardnumber.ExecuteScalar();
if(check_cardnumber.ExecuteNonQuery() != cardnumber)
{
Console.WriteLine("Create completed!");
cnn.Close();
return itExist = false;
}
else
{
Console.WriteLine("This Card Number already exist!");
itExist = true;
cnn.Close();
return itExist;
}
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Fetch Error:";
msg += ex.Message;
throw new Exception(msg);
}
finally
{
cnn.Close();
}
}
【问题讨论】:
-
What is the exception if any? In general you should do this in the database not at the client. It's always possible that multiple clients trying to insert at the same time, so you have a race condition. So provide stored-procedures which do that.
-
"and if not then add to database" < this part seem to be missing from your code.
-
I have the add to database in other funktion, this one that I have problems with are just checking if the new value that I'm trying to add exist or not. If it exist then it will send the value true back and then the other funktion will work with that. Same if it dont exist. Its just the check if exist already part that I have issue with.