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..
Related
I want to generate an automatic ID in a textbox
The table in SQL goes like
Create table employee(empid varchar(50),empname varchar(50),sal int)
And the ID has to be in the format TOO0, T001, TOO2`, and so on.
Identify the components in your 'natural' key
Your key has a string prefix to an incrementing numeric value
Find the max numeric value for all existing values with the same prefix
This is the tricky and controversial bit, you will need to query the DB for all existing keys to... something like this can work in an SQL environment
...
SELECT 'TOO' + Cast(MAX(Right(EMPID, LEN(EMPID)-3) + 1)
FROM Employee
WHERE EMPID LIKE 'TOO%'
Ideally though you should do this inside a stored procedure or in the insert statement where you can minimise or remove the risk of multiple processes generating rows with the same key.
As a double check, make sure you add a unique index constraint to the EMPID key (if it is not already your primary key)
If you are hooked on displaying the emplid to the user before the row is created, then consider a model where you insert the row first to reserve the key and the user from here is just updating the blank entry. Of course now you will need to delete the row if they choose to cancel the operation.
I am not entering into the argument of is this a good code pattern. To the coders out there who say 'Ids should only be generated in the DB' I agree but there are many valid scenarios where you may want to generate and use a 'natural' key.
I strongly recommend the use of 'surrogate' (arbitrary key generated explicitly to identify the row) keys as the primary identifier of all rows of data in the DB, this simplifies the use of ORMs and other data factory tools.
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(strConnString);
str = "select count(*) from employee";
com = new SqlCommand(str, con);
con.Open();
count = Convert.ToInt16(com.ExecuteScalar()) + 1;
txt_empid.Text = "E00" + count;
con.Close();
}
protected void btn_insert_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Data Source=HP-PC;Initial Catalog=kriti;Integrated Security=True");
con.Open();
str = "insert into employee values('" + txt_empid.Text.Trim() + "','" + txt_empname.Text.Trim() + "'," + txt_sal.Text.Trim() + ")";
com = new SqlCommand(str, con);
com.ExecuteNonQuery();
con.Close();
Label4.Text = "Records successfully Inserted";
}
This is my actual code and it is generating an error as unable to convert nvarchar value TOO1 to the data type int
I have a database named testDB, which contains table Versions, which contains a column [Release Date] with datetime format.
Now, I want to read it in my C# Windows Service:
protected void SqlConnect()
{
SqlCommand comSql;
DateTime relDate;
SqlDataReader myReader = null;
using (SqlConnection myConnection = new SqlConnection(_server +
_username +
_password +
"Trusted_Connection=yes;" +
"database=testDB; " +
"connection timeout=30"))
{
try
{
myConnection.Open();
comSql = new SqlCommand("select [Release Date] from dbo.Version",
myConnection);
myReader = comSql.ExecuteReader();
while (myReader.Read())
{
//Here's my problem, explained below
}
}
catch
{
}
finally
{
if (myReader != null) myReader.Close();
}
}
}
Now, I want to assign the value stored in that column to relDate variable. However
relDate = myReader.GetDateTime();
requires GetDateTime to have column number passed there (if I understand this right). But I already selected column in my comSql. Is this the correct way to deal with this problem, ie. just putting the column number in the code?
EDIT: Ok judging by the answers I might word this question wrong or something.
I know that I must pass the column index to GetDateTime(). I ask if there's a way to do that without hardcoding it like GetDateTime(0).
You can use GetOrdinal method on the data reader to get ordinal of the column from its string name. In that way, you won't have to hardcode the column index.
GetOrdinal is also useful when you're reading data from the data reader in a loop. You can initialize the index variable before the loop starts and then use it in every iteration of the loop.
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
I am trying to check if there is a row present in a SQL Server table or not.
If the row exists (on a particular TicketID), it should show a messagebox that you can't continue further as there is already an entry in database. But if there isn't, it should insert some records (on that particular TicketID).
I tried try and catch but wasn't able to do it :
Here is the code of query: (hardcoded ticketID for example)
bool no;
try
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ST"].ConnectionString.ToString());
con.Open();
cmd.CommandText = "SELECT EngineerVisited from tblTicketTechnical where TicketID=1";
cmd.Connection = con;
rdr = cmd.ExecuteReader();
while (rdr.Read())
{
bool = rdr.GetBoolean(0);
}
con.Close();
}
catch
{
MessageBox.Show("Cannot continue");
}
I would really appreciate if someone could suggest a function that will return true if row is found and return false, if it isn't.
You should follow the same logic in code as the logic you state in English: if there's already a ticket show a message and if not, insert some data.
var checkQuery = "SELECT COUNT(*) FROM tblTicketTechnical where TicketID=1";
var command = new OleDbCommand(checkQuery, con);
con.Open();
int count = (int)command.ExecuteScalar();
if(count > 0)
{
//Already exists, show message
}
else
{
var insertQuery = "INSERT INTO tblTicketTechnical(col1, col2) VALUES('val1', val2')";
con = new OleDbCommand(insertQuery, con);
con.ExecuteNonQuery();
}
Please mind that this is written out of my head and not tested. Nor have I implemented exception handling. This is just to show the logic how you can perform what you want to achieve.
You can use HasRows property of SQLDataReader.
A catch block will only be executed if your code throws an exception. Here it is simply not happening.
Instead of Try/Catch use if statements and checks on your query results.
Create procedure and code like this
IF NOT EXISTS (SELECT 1 FROM youtable WHERE id= #id)
BEGIN
RAISERROR ('Record Exists', 16, 2)
END
ELSE
Begin
INSERT INTO YOURTABEL(COLUM1,COLUM2) VALUES(VALUE1, VALUE2)
END
and then by try catch you can show message to user
You can use DataTableReader.HasRows Property
The HasRows property returns information about the current result set
I am dealing with the following problem:
I use a MSSQL Stored Procedure for displaying my data in a DataGridView. The Update and Insert Commands work, but there is one problem:
On inserting a new Row, the auto-numbered primary key isn't send back to my DataAdaptar. So the insertion is successfull in the database, but the PK is left blank in the DataGridView.
I allready tried some codes like:
private void _rowUpdated(object sender, SqlRowUpdatedEventArgs e)
{
if (e.Status == UpdateStatus.Continue && e.StatementType == StatementType.Insert)
{
cmd = conn.CreateCommand();
cmd.CommandText = "SELECT ##IDENTITY FROM " + e.Row.Table.TableName;
DataRow r = dt.Rows[dt.Rows.Count - 1];
r.ItemArray[0] = cmd.ExecuteScalar();
//r.SetModified(); --> err?
r.AcceptChanges();
}
}
on the DataAdapter, but nothing seems to work. All the SQL commands work fine.
When I refresh the data in the DataGridView, everyting is perfect. But the problem with this is, that the sort order and column width are adjusted. And that isn't what I want.
Can someone help me with this problem?
Looking forward for the solutions!
Thanks!
Finally found the answer and wanted to share it:
dt.RowChanged += new DataRowChangeEventHandler(_update_fields);
private void _update_fields(object sender, DataRowChangeEventArgs e)
{
try
{
if (e.Action == DataRowAction.Add)
{
conn.Open();
cmd = conn.CreateCommand();
cmd.CommandText = "SELECT IDENT_CURRENT('" + e.Row.Table.TableName + "')";
dt.Rows[dt.Rows.Count - 1][0] = int.Parse(cmd.ExecuteScalar().ToString()) + 1;
dt.AcceptChanges();
conn.Close();
}
adapt.Update(dt);
}
catch (SqlException ex)
{
Debug.WriteLine(ex.Message);
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
}
}
Hope it will save you some time! :)
Gr
VeeWee
Since the connection to sql server has terminated so ##identity will become null and hence you are getting null value.
You cannot use scope_identity() here since its scope is limited to the place i.e. procedure in your case where it is called.
ident_current() always returns last identity value for the table that you specified.
It might not work correct in case of replication
Update your commandText to ="Select ident_current("+e.Row.Table.TableName+")"
Here are the results of using various techniques of retrieving identity value.
Replace dbo.M_PatientEntry with your table name
select ident_current('dbo.M_PatientEntry')
---------------------------------------
13
select ##identity from dbo.M_PatientEntry
---------------------------------------
NULL
NULL
select scope_identity()
---------------------------------------
NULL
select scope_identity() from dbo.M_PatientEntry
---------------------------------------
NULL
NULL
Also try avoiding ##Identity rather use scope_identity() or ident_current
##identity will give you incremented value of trigger table result if you are using trigger on the same table where insertion is going on.
see this documentation