Check if player exists error - c#

I have this windows form code
private void StartGame_Click(object sender, EventArgs e)
{
if (player.Text == "")
{
MessageBox.Show("Enter A player to proceed.");
}
else
{
//SQL Connection String
using (SqlConnection conn = new SqlConnection("Data Source=Keith;Initial Catalog=SoftEngg;Integrated Security=True"))
{
conn.Open();
bool exists = false;
// create a command to check if the username exists
using (SqlCommand cmd = new SqlCommand("select * from PlayerData where PlayerName = #player", conn))
{
cmd.Parameters.AddWithValue("player", player.Text);
exists = (int)cmd.ExecuteScalar() > 0;
}
// if exists, show a message error
if (exists)
MessageBox.Show(player.Text, "is used by another user.");
else
{
// does not exists, so, persist the user
using (SqlCommand cmd = new SqlCommand("INSERT INTO PlayerData(PlayerName) values (#Playername)", conn))
{
cmd.Parameters.AddWithValue("Playername", player.Text);
cmd.ExecuteNonQuery();
}
}
conn.Close();
}
}
}
my goal is to alert the player and display the messagebox "player already exist" in the system. But my code doesn't seem to work. When I run the program I get an error over this code here:
exists = (int)cmd.ExecuteScalar() > 0;
and the error says: (Additional information: Object reference not set to an instance of an object.)
How to fix this, please help.

You should use select Count(*) from PlayerData where PlayerName = #player if you want to use ExecuteScalar

Your problem not was in the query.
i mean not in this select * from PlayerData where PlayerName = #player
you were getting the error because of exists = (int)cmd.ExecuteScalar() > 0;
Cause:
here you are trying to convert the output to Integer.
so, when cmd.ExecuteScalar() getting the null Value on that time you are getting the error.
Have to Remember
SqlCommand.ExecuteScalar:
Executes the query, and returns the first column of the first row in
the result set returned by the query. Additional columns or rows are
ignored.
you can use select * from PlayerData where PlayerName = #player but you must confirm that your first column of this table is a NonNullable column.
and your checking should be like
exists = (cmd.ExecuteScalar()!=null)?true:false;
Or, you can try by selecting your primary key column.
select your_Primary_Key_Name from PlayerData where PlayerName = #player
and check
exists = (cmd.ExecuteScalar()!=null)?true:false;
do not use AddWithValue
cmd.Parameters.Add("#player",SqlDbType.Varchar,200).Value=YourValue;

Related

Checking if int exists in array C#

I don’t know if this is the correct way to be doing this but I'm trying to get all Job Numbers from a database table and checking that what the user inputs is in the database. I’m doing this by sending all data to an array and checking if it exists in there. However I’m sure there will be an easier way. This is the code I have so far:
public class IDNo
{
public int Col1 { get; set; }
}
private void button3_Click(object sender, EventArgs e)
{
String check = "SELECT * FROM Job";
using (SqlConnection con = new SqlConnection(str))
{
using (SqlCommand cmd = new SqlCommand(check, con))
{
con.Open();
var listOfId = new List<IDNo>();
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
var id = new IDNo();
id.Col1 = Convert.ToInt32(reader["JobNo"]);
listOfId.Add(id);
}
}
string JN = textBox10.Text;
int JoNo = Int32.Parse(JN);
if (JoNo == IDNo)
{
MessageBox.Show("No job number found, please try again!");
}
else
{
DO SOMETHING HERE WHEN CORRECT
}
}
}
}
I would just like some help on how to check if the number the user inputs exists in the array.
It is the database engine that should answer your question, not simply give you back all your job records and force your code through a, possible, very lengthy search of the matching data in your records...
int JoNo;
if(!Int32.TryParse(textBox10.Text, out JoNo))
{
MessageBox.Show("Not a valid number");
return;
}
String check = #"IF EXISTS( SELECT 1 FROM Job WHERE JobNo=#num)
SELECT 1 ELSE SELECT 0";
using (SqlConnection con = new SqlConnection(str))
using (SqlCommand cmd = new SqlCommand(check, con))
{
con.Open();
cmd.Parameters.Add("#num", SqlDbType.Int).Value = JoNo;
int result = (int)cmd.ExecuteScalar();
if(result == 0)
MessageBox.Show("No job number found, please try again!");
else
.....
}
First, you test if the user input is a valid number without throwning exceptions (Int32.TryParse) but just informing your user of the error, then you build an IF EXISTS query because you are just interested to know if the job number exists or not and you don't need to retrieve that value. Finally, the execution is done using ExecuteScalar because you are interested only in getting the single value 1 (for an existing JobNo or 0 for a not exisisting JobNo.
You can use the jobNo which is sent by the user as an input parameter for your search query in database. So you can simply do it using the query:
SqlCommand check = new SqlCommand("SELECT * FROM Job where JobNo = #JobNo" , conn);
check.Parameters.AddWithValue("#JobNo", id.Text);
int exists = (int)check.ExecuteScalar();
if(exists > 0)
{
//job no exist
}
else
{
//job no doesn't exist.
}

How to check if the primary key exists in my database from a textbox (windows form), c#

I have a textbox and a button in a windows form application.
I want to check if the primary key (persId) exists in my sql database/dataset (made with Visual studio) when I enter a number in the textbox and press the button. I dont know how to compare the text with persId from the database.
If the persId exists I want to fill two textboxes in a new form and show the persId and persName.
I am new to programming in C# so I have probably missed something. I looked at how to check if value exists in database from textbox c# but could not find an answer.
Thanks in advance!
public void searchPersId(string persId)
{
SqlConnection conn = new SqlConnection();
SqlCommand myCommand = new SqlCommand("SELECT persId FROM Customers WHERE persId = #persId", conn);
myCommand.Parameters.AddWithValue("#persId", persId);
if (textBox1.Text = myCommand ) //I dont know how to compare the values of textbox with myCommand..
{
//Show values (persId and persName) in two textBoxes in a new form.
}
else
{
MessageBox.Show("The ID does not exist.");
}
}
First, use the using-statement for everything implementing IDisposable like the connection to dispose unmanaged resources and to close the connection, even in case of an error.
Then you have to open the connection and to use ExecuteReader to get a datareader to check if there's at least one record with that ID, you can use reader.HasRows. You also have to select the persName if you want it as mentioned.
using(var conn = new SqlConnection())
using(var myCommand = new SqlCommand("SELECT persId, persName FROM Customers WHERE persId = #persId", conn))
{
myCommand.Parameters.AddWithValue("#persId", persId);
conn.Open();
using(var rd = myCommand.ExecuteReader())
{
bool personExists = rd.HasRows;
if(personExists)
{
// advance the reader to the first record, presuming there is only one, otherwise use a loop while(rd.Read)
rd.Read();
string persName = rd.GetString(1); // second field
// ...
}
else
{
MessageBox.Show("The ID does not exist.");
}
}
}
You can also use ExecuteScalar
public void searchPersId(string persId)
{
SqlConnection conn = new SqlConnection();
SqlCommand myCommand = new SqlCommand("SELECT persName FROM Customers WHERE persId = #persId", conn);
myCommand.Parameters.AddWithValue("#persId", persId);
object personName = myCommand.ExecuteScalar();
if(!string.IsNullOrEmpty(personName.ToString()))
//if (textBox1.Text = myCommand) //I dont know how to compare the values of textbox with myCommand..
{
//Show values (persId and persName) in two textBoxes in a new form.
textBox2.Text = personName.ToString();
}
else
{
MessageBox.Show("The ID does not exist.");
}
}
First you have to Execute the command.
SqlDataReader dr = myCommand.ExecuteReader(CommandBehavior.CloseConnection);
if (dr.HasRows)
{
// ... if it has rows then you know it match
}
else
{
// ... data doesn't exists
}
Then you can compare the result.

comparing data of textbox with database and update database with the new value

i am trying to compare the value of textbox with the data in database, and if the value in textbox is bigger den the value of data in database, a alert message will appear and if it is smaller than the value of the data in the datebase, it will minus the database value with the value of textbox and update the value of database. there is no error but when i click on the button, nothing appear and no changes have made to the database. is there anything wrong with my code? thx
protected void btn_buy_Click(object sender, EventArgs e)
{
hookUp = new SqlConnection("Server=localhost\\SqlExpress;Database=VoteNow;" +
"Integrated Security=True" );
sqlCmd = new SqlCommand("SELECT UnitAvailable FROM stockdetails1 WHERE StockID = 3", hookUp);
hookUp.Open();
reader = sqlCmd.ExecuteReader();
int amountkey;
amountkey = Convert.ToInt32(amount.Text);
while (reader.Read())
{
int unitavailable = reader.GetInt32(0);
int unitavailable1;
if (amountkey <= unitavailable)
{
unitavailable1 = unitavailable - amountkey;
SqlCommand sqlupdateCmd = new SqlCommand("UPDATE StockDetails Set UnitAvailable = '+unitavailable1+' WHERE StockID = 3", hookUp);
sqlupdateCmd.ExecuteNonQuery();
Response.Write("<script LANGUAGE='JavaScript'> alert('The units available is enough.')</script>");
}
else
{
Response.Write("<script LANGUAGE='JavaScript'> alert('The units available is not enough.')</script>");
}
}
reader.Close();
hookUp.Close();
}
}
You are missing sqlupdateCmd.ExecuteNonQuery() after your update command.
Also, I don't understand Why you are alerting the same message again in else block of code? The other thing is, probably UnitAvailable is a single value so instead of using ExecuteReader use ExecuteScalar.
Also, consider implementing your code with using which will dispose the expensive resources such as connection and command objects.Please check this for more.
Your Javascript alert shoul look like:-
Response.Write("<script type=\"text/javascript\">alert('The units available is not enough.')</script>");
Update 2:
Please use ExecuteScalar as i mentioned above like this:-
sqlCmd = new SqlCommand("SELECT UnitAvailable FROM StockDetails WHERE StockID = 3", hookUp);
hookUp.Open();
int unitavailable = Convert.ToInt32(sqlCmd.ExecuteScalar());
int amountkey;
amountkey = Convert.ToInt32(amount.Text);
int unitavailable1;
if (amountkey <= unitavailable)
{
Response.Write("<script LANGUAGE='JavaScript'> alert('The units available is not enough.')</script>");
}
else
{
unitavailable1 = unitavailable - amountkey;
SqlCommand sqlupdateCmd = new SqlCommand("UPDATE StockDetails Set UnitAvailable = #unitavailable1 WHERE StockID = 3", hookUp);
sqlupdateCmd.Parameters.Add("#unitavailable1",SqlDbType.Int).Value = unitavailable1;
sqlupdateCmd.ExecuteNonQuery();
}
I hope u have to make two changes to the code.
U should add ExecuteNonQuery after the update statement.
Also the variable unitavailable1, which is the new available unit had been provided within the quotes..so probably the value is not substituted. Try to close the quotes before that and open it after the variable and use '+' to concatenate them like this
"UPDATE StockDetails Set UnitAvailable = "+unitavailable1+" WHERE StockID = 3".
Try this...Hope this will work...

Displaying an error message during insert execution

How do I display an error message if a student is already assigned with the position currently being inserted into the mysql database, then rollback the transaction?
If a different position is assigned, it should continue to check the next row.
Here is my code for insertion:
conn.Open();
MySqlTransaction mt = conn.BeginTransaction();
try {
for (int cnt = 0; cnt <= lv1.Items.Count - 1; cnt++) {
if (lv1.Items[cnt].SubItems[3].Text == " ")
continue;
string query = "insert into candidate(pid,s_id)values(#pid,#sid)";
MySqlCommand cmd = new MySqlCommand(query, conn);
cmd.Parameters.Add(new MySqlParameter("#pid", lv1.Items[cnt].SubItems[0].Text ));
cmd.Parameters.Add(new MySqlParameter("#sid", lv1.Items[cnt].SubItems[2].Text));
cmd.Transaction = mt;
cmd.ExecuteNonQuery();
}
mt.Commit();
} catch (Exception error) {
MessageBox.Show(error.Message);
mt.Rollback();
}
conn.Close();
This is my dummy student table:
This is my dummy position table:
This is my dummy candidate table:
This is my listview control sample:
Don't rely on an exception from the insert statement: if you don't insert anything, there is no need to perform a rollback.
Instead, check to see if the item already exists and only insert if it does not. If you need to tell the user that it already exists, you can show the message box.
For example:
// This is just an example; not sure what exact conditions you need
var cmdExists = new MySqlCommand("SELECT 1 FROM candidate WHERE pid = #pid");
cmdExists.Parameters.Add(new SqlParameter("#pid", lv1.Items[cnt].SubItems[0].Text));
if (cmdExists.ExecuteScalar() == DBNull.Value)
{
string query = "insert into candidate(pid,s_id)values(#pid,#sid)";
...
} else {
MessageBox.Show("some error message that makes sense to your user");
}

checking if record exists in Sqlite + C#

I'm trying to check if a record in a table already exists.
How could I do that?
I already wrote the following code:
string dbName = "Data Source=searchindex.db";
SQLiteConnection con = new SQLiteConnection(dbName);
con.Open();
SQLiteCommand cmd = new SQLiteCommand(con);
// If this sql request return false
cmd.CommandText = "SELECT rowid FROM wordlist WHERE word='word'";
cmd.ExecuteNonQuery();
// then add record in table
cmd.CommandText = "INSERT INTO wordlist(word) VALUES ('word')";
To check if that record exists you could simplify your code
cmd.CommandText = "SELECT count(*) FROM wordlist WHERE word='word'";
int count = Convert.ToInt32(cmd.ExecuteScalar());
if(count == 0)
{
cmd.CommandText = "INSERT INTO wordlist(word) VALUES ('word')";
cmd.ExecuteNonQuery();
}
ExecuteScalar will return the first column on the first row returned by your query.
(The link is for SqlServer, but it is identical for SQLite, because the SQLiteCommand should implement the IDbCommand interface)
Another approach to use is the following
cmd.CommandText = "INSERT INTO wordlist (word)
SELECT ('word')
WHERE NOT EXISTS
(SELECT 1 FROM wordlist WHERE word = 'word');";
cmd.ExecuteNonQuery();
This is even better because you use a single query and not two (albeit the difference in a local db should be minimal)
insert into wordlist(word)
select 'foo'
where not exists ( select 1 from wordlist where word = 'foo')
If you are using sqlite-net-pcl you could write the following.
I have a base class for several tables and in it, I have a RowExists method.
The relevant source code looks as follows:
public abstract class BaseSQLiteAccess
{
protected SQLiteConnection _databaseConnection;
protected String TableName { get; set; }
//...
protected bool RowExists(int id)
{
bool exists = false;
try
{
exists = _databaseConnection.ExecuteScalar<bool>("SELECT EXISTS(SELECT 1 FROM " + TableName + " WHERE ID=?)", id);
}
catch (Exception ex)
{
//Log database error
exists = false;
}
return exists;
}
}

Categories

Resources