I using this code to entering .
private void button1_Click(object sender, EventArgs e)
{
string Coonstring = "datasource=localhost;port=3306;username=root;password=****;Charset=utf8";
string cmd = "Insert into project.name_registry (name ) values('" + this.txt.Text + "');";
MySqlConnection connectionDatabase = new MySqlConnection(Coonstring);
MySqlCommand cmddata = new MySqlCommand(cmd, connectionDatabase);
MySqlDataReader myreader;
try
{
connectionDatabase.Open();
myreader = cmddata.ExecuteReader();
MessageBox.Show("Done");
while (myreader.Read())
{
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
I need when press on this button check if the insert name found messagebox appear tell my the name exists and prevent the add. If not tell me the insert Done. How i can do this.
Regards
The best place to have this sort of check is in the database itself. Almost all databases can set a UNIQUE constraint on a field. If you set the name column in the name_registry to be unique, the DBMS won't let you add a second entry with the same name, and an exception will be thrown. This will usually be the best way.
If the DB isn't in your hands and you can't set the column to be unique, you can use the suggestion that #FrancisDucharme and others and query the DB for the given name, and only call the INSERT if it returns 0 results:
SELECT COUNT(*) FROM name_registry WHERE [name] = 'TheName'
Note, though that there's no need to call ExecuteReader, not for this single-result SELECT statement, nor for the INSERT statement above - you should call ExecuteScalar, which will return the single-value result without loading a full-scale DataReader that you don't really need.
And lastly, as an addition to the answer, I can't in good conscience let you go on without pointing you in the direction of at least one tutorial about using parameterized queries in ADO.NET, which not only help prevent SQL injection attacks, but also help clean up the code and make it more readable, in my opinion. There are many out there.
Firstly, As previously stated: You have MAJOR SQL Injections visible...
Secondly, You should be using params.
Third, If you
SELECT *
FROM [TABLE]
WHERE [ColumnName] = #Param
Related
What am I doing wrong?
I am working on creating a windows forms C# application that is database centered. In my forms app I have 4 textboxes that inserts its data into one simple Database table.
If i type something into textBox1(Customer_Name), and I click on a button called "Check and Save', I would like the action to check if the Customer_Name exists.
If it does not exist, it should insert the data into the database.
If it does exist, it should update my database with the information entered into textBox1-4
I have this code:
private void Button1_Click(object sender, EventArgs e)
{
con.Open();
SqlCommand cmd = new SqlCommand("IF NOT EXISTS (SELECT * FROM [Customers] WHERE Customer_Name=#aa BEGIN INSERT INTO [Customers](Customer_Name,Cellphone_Number,Telephone_Number,Alternative_Number) VALUES(#aa,#bb,#cc,#dd) END ELSE BEGIN UPDATE [Customers] SET Customer_Name=#aa, Cellphone_Number=#bb, Telephone_Number=#cc, Alternative_Number=#dd END", con);
cmd.Parameters.AddWithValue("#aa", textBox1.Text);
cmd.Parameters.AddWithValue("#bb", textBox2.Text);
cmd.Parameters.AddWithValue("#cc", textBox3.Text);
cmd.Parameters.AddWithValue("#dd", textBox4.Text);
con.Close();
}
No information gets entered into the database on button click not does any information update.
What am I doing wrong?
You are not executing the command.
Your code should have a cmd.ExecuteNonQuery(); once the command is fully configured.
However, once you add that, you will get a syntax error message from SQL Server.
This is because you are missing a closing parenthesis for the Exists operator.
Please note that is far from being the only thing you are doing wrong in this code:
you are mixing UI code with application code.
you are using a global variable (or at the very least a field) to hold your instance of the SqlConnection.
you are using terrible names for your parameters and texboxes.
You are using AddWithValue.
the pattern for "upsert" you are using is cumbersome and potentially problematic.
Here are better alternatives:
First
You should read about the n-tier architectural pattern.
For winforms, it's usually implemented using MVP.
For one thing, instead of sending textboxes data directly into your database, create a Customr class to hold the data, and use that to pass customer data around in your code.
Second
Best practice is to use a local variable inside a using statement to ensure disposale of the SqlConnectioninstance and the return of the underlying connection to the connection pool.
Third
Imagine having to change something in a code that looks like this vs. changing something in a code that looks like that:
cmd.Parameters.Add(#"CustomerName", SqlDbType.NVarChar).Value = customerName;
Now you don't have to read at the SQL to figure out what that parameter means -
the less time and effort you have to spend understanding the code the better.
Fourth
The article in the link explains why it's problematic in details,
but the main point is that the data type of the parameter must be inferred from usage,
and that might yield errors because of data type wrongly inferred - or even worst - wrong data silently entered into the database.
Fifth
A better pattern is to first update, and then insert conditionally - like demonstrated in Aaron Bertrand's answer here - and in a multi-user (or multi-threaded) environment wrap the entire thing in a transaction.
All that being said, a revised code should look more like this:
private void AddOrUpdateCustomer(Customer customer)
{
// Data validity tests omitted for brevity - but you should ensure
// customer has all it's properties set correctly.
// Readable, properly indented code - Isn't that much easier to debug?
var sql = #"
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;
BEGIN TRANSACTION;
UPDATE [Customers]
SET
Cellphone_Number = #Cell,
Telephone_Number = #Telephone,
Alternative_Number = #Alternative
WHERE Customer_Name = #Name
IF ##ROWCOUNT = 0
BEGIN
INSERT INTO [Customers](Customer_Name, Cellphone_Number, Telephone_Number, Alternative_Number)
VALUES(#Name, #Cell, #Telephone, #Alternative)
END
COMMIT TRANSACTION;";
// connectionString should be obtained from configuration file
using(var con = new SqlConnection(connectionString))
{
using(var cmd = new SqlCommand(sql, con))
{
cmd.Parameters.Add(#"Name", SqlDbType.NVarChar).Value = customer.Name;
cmd.Parameters.Add(#"Cell", SqlDbType.NVarChar).Value = customer.Cellphone;
cmd.Parameters.Add(#"Telephone", SqlDbType.NVarChar).Value = customer.Telephone;
cmd.Parameters.Add(#"Alternative", SqlDbType.NVarChar).Value = customer.AlternativeNumber;
con.Open();
cmd.ExecuteNonQuery();
}
}
}
I checked your code there are few problems.
private void button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
con.Open();
SqlCommand cmd = new SqlCommand("IF NOT EXISTS (SELECT * FROM [Customers] WHERE Customer_Name=#aa BEGIN INSERT INTO [Customers](Customer_Name,Cellphone_Number,Telephone_Number,Alternative_Number) VALUES(#aa,#bb,#cc,#dd) END ELSE BEGIN UPDATE [Customers] SET Customer_Name=#aa, Cellphone_Number=#bb, Telephone_Number=#cc, Alternative_Number=#dd END", con);
cmd.Parameters.AddWithValue("#aa", textBox1.Text);
cmd.Parameters.AddWithValue("#bb", textBox2.Text);
cmd.Parameters.AddWithValue("#cc", textBox3.Text);
cmd.Parameters.AddWithValue("#dd", textBox4.Text);
cmd.ExecuteNonQuery();
con.Close();
}
There is a missing bracket and condition is missing in update statement. I have fixed the query. You can try again and also check the SQL Connection string.
IF NOT EXISTS (SELECT * FROM [Customers] WHERE Customer_Name=#aa) BEGIN INSERT INTO [Customers](Customer_Name,Cellphone_Number,Telephone_Number,Alternative_Number) VALUES(#aa,#bb,#cc,#dd) END ELSE BEGIN UPDATE [Customers] SET Customer_Name=#aa, Cellphone_Number=#bb, Telephone_Number=#cc, Alternative_Number=#dd WHERE Customer_Name=#aa END
Insert Data
Update Data
I have not check the SQL statement.
But can you check the code after adding, because without Executing the command Database you can not see changes.
cmd.ExecuteNonQuery();
before
con.Close();
Hello so i m creating a registration form in C# with MySql so it connects to the database and everything but i get this error Napaka pri registraciji Unknown column " in 'field list' the translation of Napaka pri registraciji means Error at registering i just have it in my language. I get this error when i insert data in textboxes and press Register..
the code:
private void btn_Reg_Click(object sender, EventArgs e)
{
MySqlConnection dataConnection = new MySqlConnection();
dataConnection.ConnectionString = "datasource=localhost;port=3306;username=root;password=";
dataConnection.Open();
MySqlTransaction transakcija = dataConnection.BeginTransaction();
MySqlCommand dataCommand = new MySqlCommand();
dataCommand.Connection = dataConnection;
dataCommand.Transaction = transakcija;
try
{
dataCommand.CommandText = "Insert INTO lr.users (upIme,geslo) VALUES (`"+this.tB_upIme.Text+"`,`"+this.tB_geslo.Text+"`)";
dataCommand.CommandType = CommandType.Text;
dataCommand.ExecuteNonQuery();
transakcija.Commit();
MessageBox.Show("Registracija uspešna!");
}
catch (Exception eks)
{
transakcija.Rollback();
MessageBox.Show("Napaka pri registraciji\n" + eks.Message);
}
finally
{
dataCommand.Connection.Close();
}
}
There are two things I immediately see wrong here...
First, you're using back ticks to wrap your values. In MySQL Back ticks represent database objects, so the query is looking for objects named by those values instead of using the values themselves. So instead of this:
`"+this.tB_upIme.Text+"`
You'd want this:
'"+this.tB_upIme.Text+"'
Second, and vastly more importantly, your code is wide open to SQL injection attacks. You'll want to use query parameters, not direct string concatenation. While it may look like you're just putting values into the query string, you're actually taking user input and treating it as executable code in your query string, which means users can run any arbitrary code they want on your database.
First, add parameters to your query:
"Insert INTO lr.users (upIme,geslo) VALUES (#upIme, #geslo)"
(You'll notice this also makes the query a heck of a lot cleaner and easier to read.) Then add your parameters to the command:
dataCommand.Parameters.AddWithValue("#upIme", this.tB_upIme.Text);
dataCommand.Parameters.AddWithValue("#geslo", this.tB_geslo.Text);
Then when you execute that command it will treat the user-input values as values instead of as executable code.
Change to single quotes ' in the values.
dataCommand.CommandText =
"Insert INTO lr.users (upIme,geslo)
VALUES ('"+this.tB_upIme.Text+"','"+this.tB_geslo.Text+"');";
I'm currently polishing a C# app in relation with a SQL-Server base.
It's quite simple, you can add or remove entries from the SQL table via some fields from the application.
Question is :
On a Delete action, I've made this kind of query :
DELETE FROM table
WHERE ID = #ID
It deletes what I ask it to delete, BUT what if the query doesn't find anything in the DB ?
How can I detect that ?
Because in this case, the application deletes nothing, and no exception is raised.
To make it short, I'd just like to tell the user that there's nothing to delete in this case.
If you are using SqlCommand object, there is a method called ExecuteNonQuery. The method return how many rows are affected. So, zero means none.
private static void CreateCommand(string queryString,
string connectionString)
{
using (SqlConnection connection = new SqlConnection(
connectionString))
{
SqlCommand command = new SqlCommand(queryString, connection);
command.Connection.Open();
int rowsAffected = command.ExecuteNonQuery(); // <== this
}
}
delete from table where ID=#id
select ##rowcount
This will return how many rows there were actually deleted. You do not need the exists.
have a look at ##ROWCOUNT variable
http://technet.microsoft.com/en-us/library/ms187316.aspx
I am making a Login Page. For that i am going to do authenticate the username and password from database. As i execute the program query will run and it return a -1 value. As the username and password is correct. Please Help me out. My program code is as Follow:
public partial class Home : System.Web.UI.Page
{
SqlConnection objcon;
String query;
SqlCommand cmd;
int num;
//SqlDataAdapter DataAdapter;
protected void Page_Load(object sender, EventArgs e)//db open in page load.
{
objcon = new SqlConnection("Data Source String");
objcon.Open();
}
//query execution and authentication on button click
protected void Button1_Click(object sender, EventArgs e)
{
query = "select * from tbl_user where UserName='" + txtUname.Text + "' and Password='" + txtPwd.Text + "'";
cmd = new SqlCommand(query,objcon);
num = cmd.ExecuteNonQuery();
//Label3.Text = num.ToString();
if (num == -1)
Label3.Text = "Correct";
else
Label3.Text = "Incorrect";
objcon.Close();
}
}
Look at this code:
num = cmd.ExecuteNonQuery();
Now given that you're creating a command based on a variable called query, do you really think calling a method with the phrase non-query in it makes sense? From the docs for ExecuteNonQuery, if you're not convinced yet:
For UPDATE, INSERT, and DELETE statements, the return value is the number of rows affected by the command. [...] For all other types of statements, the return value is -1.
Your statement is a SELECT query, so it's returning -1 exactly as documented.
I suspect you should be using ExecuteScalar or ExecuteReader. For example, if you're trying to get the number of matches, you should use:
SELECT COUNT(*) ... (rest of query, parameterized of course)
Personally I prefer that over taking -1 or null as per James's answer, but it's a matter of taste.
If you're not trying to get the count of matches, it's not clear why you're assigning to an int variable in the first place.
EDIT: Additional issues: (As already mentioned in comments)
Only create and open the SqlConnection when you need to, not in the constructor
Use using directives for both the SqlConnection and SqlCommand to they're closed even when there's an exception
Don't include user input directly in SQL - use parameterized SQL instead, to SQL avoid injection attacks, improve code/data separation, and avoid conversion errors
Don't store your users' password directly in the database in plaintext - that's a really horrible thing for any web site to do.
Don't try to write your own user authentication code in the first place - it's been done for you already, in many different places
What you want is to execute a scalar query, meaning that it returns a single value. In the case of your query, if the username and password match, simply select -1:
SELECT -1 FROM tblUser WHERE Username = 'James' AND Password = 'Johnson'
If a value is returned, that value will be -1 and you know you have a match. If no value (null) is returned it didn't match.
EDIT
Aside from just answering your question, there are some major problems with your code that you need to address:
You're opening a new connection each time the page loads. That's a big no-no! Not only are you opening a new connection on each page load, but you're also not closing the connection once the query has executed.
Instead of using concatenation to build your query, use a parameterized query to avoid the risk of SQL injection. Someone with even a little knowledge of SQL could easily escape your query and wreak havoc on your data.
I have a table name AVUKAT and it's columns (AVUKAT, HESAP(Primary KEY), MUSTERI)
All MUSTERI has a one unique HESAP (int).
Simple I have a page like this.
First dropdown is selected MUSTERI, second is AVUKAT
And i automaticly calculating HESAP (int and Primary KEY) with this code. (On the background.)
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
string strConnectionString = ConfigurationManager.ConnectionStrings["SqlServerCstr"].ConnectionString;
SqlConnection myConnection = new SqlConnection(strConnectionString);
myConnection.Open();
string hesapNo = DropDownList1.SelectedItem.Value;
string query = "select A.HESAP_NO from YAZ..MARDATA.S_TEKLIF A where A.MUS_K_ISIM = '" + hesapNo + "'";
SqlCommand cmd = new SqlCommand(query, myConnection);
if (DropDownList1.SelectedValue != "0" && DropDownList2.SelectedValue != "0")
{
Add.Enabled = true;
Label1.Text = cmd.ExecuteScalar().ToString();
}
else
{
Add.Enabled = false;
}
Label1.Visible = false;
myConnection.Close();
}
I just calculating HESAP with this code.
And my ADD button click function is;
protected void Add_Click(object sender, EventArgs e)
{
try
{
string strConnectionString = ConfigurationManager.ConnectionStrings["SqlServerCstr"].ConnectionString;
SqlConnection myConnection = new SqlConnection(strConnectionString);
myConnection.Open();
string hesap = Label1.Text;
string musteriadi = DropDownList1.SelectedItem.Value;
string avukat = DropDownList2.SelectedItem.Value;
SqlCommand cmd = new SqlCommand("INSERT INTO AVUKAT VALUES (#MUSTERI, #AVUKAT, #HESAP)", myConnection);
cmd.Parameters.AddWithValue("#HESAP", hesap);
cmd.Parameters.AddWithValue("#MUSTERI", musteriadi);
cmd.Parameters.AddWithValue("#AVUKAT", avukat);
cmd.Connection = myConnection;
SqlDataReader dr = cmd.ExecuteReader(System.Data.CommandBehavior.CloseConnection);
Response.Redirect(Request.Url.ToString());
myConnection.Close();
}
catch (Exception)
{
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), " ", "alert('Bu Müşteri Zaten Mevcut!')", true);
}
}
The reason use try catch , if anybody try to add add with same HESAP (int) value for the MUSTERI i want show an error message and don't add the table.
But when i try to add same MUSTERI (also same HESAP) adding same MUSTERI with HESAP=0 value.
How can i prevent this situation? I select HESAP column is Primary KEY, but still add same MUSTERI.
There's nothing too obvious here that explains the behaviour you're seeing. The most likely problem really is that the value of Label1.Text is 0 before the insert is executed, maybe set somewhere else in the ASP.NET page lifecycle. To make sure add a line of code after hesap is initialised in Add_Click like...
Response.Write("<strong>hesap == " + hesap + "</strong>");
...and comment out the Response.Redirect so you can see the output.
There are also some improvements you can make to the code to make problems less likely to occur.
It's really important that you sanitise the input to avoid SQL injection. Hopefully you're already doing this elsewhere that's not shown in your code snippet. If you don't know what this is then there's heaps of questions about it here on SO.
Also, you're not doing a query for the purpose of retrieving any rows, so use ExecuteNonQuery. So I'd also replace this line...
SqlDataReader dr = cmd.ExecuteReader(System.Data.CommandBehavior.CloseConnection);
...with...
int numberOfRows = cmd.ExecuteNonQuery();
Then check the value of ExecuteNonQuery to ensure numberOfRows == 1 so you know something actually happened.
You should also wrap your SqlConnection and SqlCommand initialisers with using statements. This means that they will automatically be disposed even if something goes wrong. This will prevent memory issues and problems with connections being left open.
Finally, let the exception value flow through into the catch statement by changing that line to catch (Exception ex). Output the exception using ex.ToString() to see all of its details. Right now you don't know what might have gone wrong if an exception occurs.
HESAP is the primary key. However, does MUSTERI also have a Unique constraint which prevents someone from entering two MUSTERI values? That would at least prevent the data from getting into the database. So something like:
Alter Table AVUKAT Add Constraint UC_AVUKAT Unique ( MUSTERI )
Is there a CHECK constraint on HESAP which requires that the value be greater than zero? So something like:
Alter Table AVUKAT Add Constraint CK_AVUKAT_HESAP Check ( HESAP > 0 )
It should be noted that MySQL will ignore Check constraints. Thus, you would need to enforce this rule in a Trigger. However, many database systems such as SQL Server, Oracle, Postgres, Informix and others will enforce check constraints.
I would make the following revisions
I would alter the query to check for whether the value exists.
I would incorporate the using statement to ensure that my objects were disposed.
I would use ExecuteNonQuery and use the number of rows returned to determine if query did not insert anything rather than implementing a global catch-all. Unless you know exactly which error you expect, you should not use Catch ( Exception ) to catch any exception no matter the type.
protected void Add_Click(object sender, EventArgs e)
{
string strConnectionString = ConfigurationManager.ConnectionStrings["SqlServerCstr"].ConnectionString;
using( SqlConnection myConnection = new SqlConnection(strConnectionString) )
{
myConnection.Open();
string hesap = Label1.Text;
string musteriadi = DropDownList1.SelectedItem.Value;
string avukat = DropDownList2.SelectedItem.Value;
string sql = #"INSERT INTO AVUKAT( MUSTERI, AVUKAT, HESAP)
Select #MUSTERI, #AVUKAT, #HESAP
From ( Select 1 As Value ) As Z
Where Not Exists (
Select 1
From AVUKAT As T1
Where T1.HESAP = #HESAP
)";
using ( SqlCommand cmd = new SqlCommand(sql, myConnection) )
{
cmd.Parameters.AddWithValue("#HESAP", hesap);
cmd.Parameters.AddWithValue("#MUSTERI", musteriadi);
cmd.Parameters.AddWithValue("#AVUKAT", avukat);
cmd.Connection = myConnection;
int rowsAffected = cmd.ExecuteNonQuery();
if ( rowsAffected = 0 )
// tell user that ID exists and their data couldn't be inserted.
Response.Redirect(Request.Url.ToString());
myConnection.Close();
}
}
}
When you eliminate the impossible, whatever remains, however improbable, must be the truth.
If the HESAP value being inserted is zero, then Label1.Text must contain a zero when the Add_Click event is fired. Looking at your DropDown event handler, there are a couple of items of note.
If HESAP is supposed to be an integer, you should verify that it is an integer using int.TryParse.
The query should be parameterized. Even the contents of a DropDownList should be considred user input.
As before, it is best to incorporate the using construct.
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
int avukat;
int hesapNo;
bool enabled = int.TryParse( DropDownList1.SelectedItem.Value, out hesapNo )
&& int.TryParse( DropDownList2.SelectedItem.Value, out avukat )
&& hesapNo != 0
&& avukat != 0;
if ( enabled )
{
string strConnectionString = ConfigurationManager.ConnectionStrings["SqlServerCstr"].ConnectionString;
using( SqlConnection myConnection = new SqlConnection(strConnectionString) )
{
myConnection.Open();
string query = #"Select A.HESAP_NO
From YAZ..MARDATA.S_TEKLIF A
Where A.MUS_K_ISIM = #HesapNo"
using( SqlCommand cmd = new SqlCommand(query, myConnection) )
{
cmd.AddParameterWithValue( "#HesapNo", hesapNo );
Label1.Text = cmd.ExecuteScalar().ToString();
}
}
}
Add.Enabled = enabled;
Label1.Visible = false;
}
If you add the CHECK constraint I mentioned at the top, then the code will error on insert and the bad row will not get into the database. That should lead you back to the DataSource for DropDownList1. It would appear that its SelectedValue is being returned as zero. That would imply that source that populates DropDownList1 is pushing a value with zero in it. What is the source that populates DropDownList1?
Hi soner
To insert record in database we have call cmd.executenonreader() methods
I think that is problem please chek it & let me know.
Maybe you should try to insert a sample data directly to your database and try to test adding same MUSTERI and HESAP to the table. You should get an error.
And i think you should modify your query for inserting data at Add_Click
SqlCommand cmd = new SqlCommand("INSERT INTO AVUKAT VALUES (#MUSTERI, #AVUKAT, #HESAP)", myConnection);
it should be:
SqlCommand cmd = new SqlCommand("INSERT INTO AVUKAT (MUSTERI, AVUKAT, HESAP) VALUES (#MUSTERI, #AVUKAT, #HESAP)", myConnection);
Hope this helps
Without looking at your database schema, it's difficult to make any kind of real guess about what's going on here, but I might propose the following.
Does your database have unique indexes set up for the two values that you don't want to duplicate?
Is your database table set up so that primary keys are auto-generated, or are you manually managing primary keys?
Are any triggers causing the issue?
Are you certain that the code responsible for displaying the primary key column is retrieving it correctly in all scenarios?
Has the insert actually occurred? If the insert hasn't occurred, you're seeing the default value for integral values, which would be zero.
My next step would be to fire up profiler and find out what your application is ACTUALLY sending to SQL Server. Make sure the values coming in are what you expect them to be, then execute the query directly in SSMS/QA to make sure it behaves as expected.
I'm with Alex in that the culprit is probably an unexpected value in your label. Find out for sure what SQL Server is seeing so you know which value needs more attention throughout the page life cycle.
While trying to add the duplicate record, are you selecting value in both the drop-downs? I can make a wild guess that your second drop-down for AVUKAT is not selected and hence your Label1.Text is set to null resulting in 0 being inserted for primary key.
If error is in add button event, then the evil is Response.Redirect(Request.Url.ToString()); swap the connection.close() and response.redirect. because after page redirection the myconnection object is lost.
That should be this manner
myconnection.close();
Response.redirect("url",false);
i think it will work..