regarding the generation of an automatic id - c#

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

Related

System.Data.SqlClient.SqlException: 'Incorrect syntax near the keyword 'where'.' ||||who can help me with this error?

the code is below and the error starting from sqlCommand cmd the 13th line of this code
private void button2_Click(object sender, EventArgs e)
{
if (StudenUsn.Text == "" )
{
MessageBox.Show("Enter The Student Number");
} else {
Con.Open();
String query = "update Student_tbl set StdName='" + StudName.Text + "',where FatherName='" + FtName.Text + "',where MotherName='" + MtName.Text + "',where StdAddress='" + Address.Text + "',where Collage ='" + Collage.Text + "'set StdRoom = " + StRmNum.SelectedValue.ToString()+",StdStatus = '"+ StudSt.SelectedItem.ToString() + "' where StdUsn ='"+StudenUsn+ "')";
SqlCommand cmd = new SqlCommand(query, Con);
cmd.ExecuteNonQuery();
MessageBox.Show("Room Successfully Updates");
Con.Close();
FillStudentDGV();
}
}
Your code should look more like:
private void button2_Click(object sender, EventArgs e)
{
if (StudenUsn.Text == "" )
{
MessageBox.Show("Enter The Student Number");
} else {
var query = #"
update Student_tbl
set
StdName=#sn,
FatherName=#fn,
MotherName=#mn,
StdAddress=#sa,
Collage=#c,
StdRoom=#sr,
StdStatus=#ss
where
StdUsn=#su";
using var con = new SqlConnection(YOUR_CONN_STR_HERE);
using var cmd = new SqlCommand(query, con);
cmd.Parameters.AddWithValue(#sn, StudName.Text);
cmd.Parameters.AddWithValue(#fn, FtName.Text);
cmd.Parameters.AddWithValue(#mn, MtName.Text);
cmd.Parameters.AddWithValue(#sa, Address.Text);
cmd.Parameters.AddWithValue(#c, Collage.Text);
cmd.Parameters.AddWithValue(#sr, StRmNum.SelectedValue);
cmd.Parameters.AddWithValue(#ss, StudSt.SelectedItem);
cmd.Parameters.AddWithValue(#su, StudenUsn);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Room Successfully Updates");
FillStudentDGV();
}
}
There are good reasons to avoid using AddWithValue if you use SQLServer which you can get into at a later date if you want, but it's convenient for me (who doesn't know the types and widths of your columns) dealing with the current massive elephant in the room which is your SQL is massively vulnerable to a hacking technique known as sql injection (and to a lesser extent it would blow up with an error for any student whose name included an apostrophe) - using AddWithValue might make your query slightly slower, but better that than it be the cause of the next data breach; learn how to write SQLs right, right now
Never ever take data supplied by a user and concatenate it into an SQL string. Doing so essentially, in most cases, gives the user access to your database. So many big companies whose developers should know better, put up expensive firewalls and security and then let anyone in via this back door anyway; sql injection prone systems are one of the leading causes of hacks in the world today
Always use #parameter placeholders in the SQL for user data and add a parameter to the command's parameters collection, containing the data
Now on the topic of your actual error; the pattern for an update is
update table
set col1=#param1, col2=#param2 ...
where (some conditions)
You have one where and one set. If there is some conditional aspect to your set, like you only want to update the student name/address if it is currently null then you can do like:
update table
set
name=case when name is null then #n else name end,
address=case when address is null then #a else address end
where (some conditions)
Or more simply
update table
set
name=coalesce(name, #n)
address=coalesce(address, #a)
where (some conditions)
You can't mix n match and say "where this=that where this2=that2 set this3=that3" - that's a syntax error. Where is for picking the row you want to update and set is for starting a block of commas separated columns and values the row data is to be updated to.
Strive to write your sql nicely formatted inside an #string; it's a programming language all of its own, and will be easier to debug if it's laid out nicely
Can u try with it ?
String query = "update Student_tbl set StdName='" + StudName.Text + "',StdRoom = '" + StRmNum.SelectedValue.ToString()+"',StdStatus = '"+ StudSt.SelectedItem.ToString() + "' where FatherName='" + FtName.Text + "' and MotherName='" + MtName.Text + "' and StdAddress='" + Address.Text + "' and Collage ='" + Collage.Text + "' and StdUsn ='"+StudenUsn+ "'";

How to insert data in single column(cell) of new row in c#?

I have an .accdb file with four tables in it
Product_Particulars
Cust_Details
Variable_fields
Permanant_fields
The number of column in the 'Variable_fields' table is not fixed (changed using 'ALTER TABLE' OleDb nonQuery). But it has two fixed columns 'Tranx_ID', 'Tranx_time'.
I want to accomplish something that will enable me to add data in the 'Tranx_ID' Column in a new row from a textBox without caring about other columns in the table (i.e. other cells in that row, in which the 'textBox.Text' is attempted to insert) and save the row with data in only one cell.
N.B.: I am actually using OleDb & I will use the 'Tranx_ID' for Updating that particular row using an OleDbCommand like,
"UPDATE Variable_fields " +
"SET [This column]='" +thistxtBx.Text +
"',[That column]='" +thattxtBx.Text +
"'WHERE ([Tranx_ID]='" +textBox.Text+ "')";
The exception is caused by the fact that one or more of the columns that you don't insert cannot have NULL as value. If you can remove this flag and allow a null value then your INSERT could work or not for other reasons.
Indeed you use a string concatenation to build your query and this is a well known source of bugs or a vector for an hacking tecnique called Sql Injection (I really suggest you to document yourself about this nasty problem)
So your code could be the following
string query = #"UPDATE Variable_fields
SET [This column]= #this,
[That column]=#that
WHERE ([Tranx_ID]=#trans";
using(OleDbConnection con = new OleDbConnection(....constringhere....))
using(OleDbCommand cmd = new OleDbCommand(query, con))
{
con.Open();
cmd.Parameters.Add("#this", OleDbType.VarWChar).Value = thisTextBox.Text;
cmd.Parameters.Add("#that", OleDbType.VarWChar).Value = thatTextBox.Text;
cmd.Parameters.Add("#trans", OleDbType.VarWChar).Value = transTextBox.Text;
int rowsInserted = cmd.ExecuteNonQuery();
if(rowsInserted > 0)
MessageBox.Show("Record added");
else
MessageBox.Show("Record NOT added");
}
Helpful links:
Sql Injection explained
Give me parameterized query or give me death
Using statement

How do I auto-generate an ID in my WPF DataGrid when entering in new fields

What I want to do is when the person goes to enter in a new data to create a new row in the database / DataGrid. I want the ID to be auto generated. I do not want the users to be putting in their own ID. Except, I don't really have any idea of how to do this.
I have tried researching on how to do this, and have had no luck at all.
This is what I have for adding the rows into the DataGrid and database.
private void addRows_Click(object sender, RoutedEventArgs e)
{
SqlConnection conn = new SqlConnection(sqlstring);
conn.Open();
string Query = "Insert into [ASSIGNMENT] ([AssignmentID], [Description], [TotalPoints], [PointsEarned], [GradeBucketID]) Values('" + this.txtAssignment.Text + "','" + txtDescription.Text + "','" + txtTotalPoints.Text + "','" + txtPointsEarned.Text + "', '" + txtGradeBucket.Text + "')";
SqlCommand createCommand = new SqlCommand(Query, conn);
createCommand.ExecuteNonQuery();
MessageBox.Show("Updated");
conn.Close();
}
Note: This is WPF and a DataGrid. Not WinForm and DataGridView. There is a difference.
Any help with this will be greatly appreciated! Thanks!
the best way is to configure you table in database to auto generate the key I mean Identity and not insert any value for unique column and let the table to auto generate it
Just define the ID filed in the database as an automatic field.
In Access is an AutoNumber, in MySQL is to give the auto_increment attribute to the field and so on.
You could also use the globally unique identifier (GUID) to generate a unique id :
var ID = Guid.NewGuid().ToString();

Conversion failed when converting date and/or time from character string C#

I would like a help please. When I want insert datetimepicker value into my table but he doesn't can insert and he show me a message
Conversion failed when converting date and/or time from character
string
You can help me please !
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void add_Click(object sender, EventArgs e)
{
cmd.CommandText = "Insert into clients values (" + cintxt.Text + ", '" + nomtxt.Text + "', '" + prntxt.Text + "', '" + datenaiss.Value + "', '" + addtxt.Text + "', '" + teltxt.Text + "')";
cnx.Open();
cmd.ExecuteNonQuery();
cnx.Close();
}
Your code that tries to insert the record should be changed to use a parameterized approach.
This could be an example
private void add_Click(object sender, EventArgs e)
{
string commandText = #"Insert into clients values
(#id, #name, #prn, #datan, #addr, #tel)";
using(SqlConnection cnx = new SqlConnection(connectionString))
using(SqlCommand cmd = new SqlCommand(commandText, cnx)
{
cmd.Parameters.AddWithValue("#id", Convert.ToInt32(cintxt.Text));
cmd.Parameters.AddWithValue("#name", nomtxt.Text);
cmd.Parameters.AddWithValue("#prn", prntxt.Text);
cmd.Parameters.AddWithValue("#datan", datenaiss.Value);
cmd.Parameters.AddWithValue("#addr", addtxt.Text);
cmd.Parameters.AddWithValue("#tel", teltxt.Text );
cnx.Open();
cmd.ExecuteNonQuery();
}
}
In this code I have changed something. First, the connection and the command are no more global variables but just local and are enclosed in a using statement that ensure a proper closing and disposing also if, for any reason, the code throws an exception.
Second the command text is no more a concatenation of strings, but it is only a single string with parameters placeholders. Concatenating string to build command texts is really a bad practice. Sql Injection hackers wait for commands built in this way to hit your database and, as you have already seen, more often than not, the underlying datatable doesn't understand a string that represent a date to be a valid date.
Finally the command parameters collection is filled with a parameter for every field expected by the command text placeholders. Notice that in this way you build parameters that are of the datatype of the value passed not simply strings that are not expected by the datatable fields. Of course in your actual situation it is possible that some of these parameters should be changed to match exactly your datatable field (for example I don't know id the first field is an integer or not)
EDIT As requested by comments below I add also some considerations on the method AddWithValue.
While it is convenient and expressive it could be a problem if your program call this code with frequency or if your database is under heavy use. The preferred method to use is
cmd.Parameters.Add("#name", SqlDbType.NVarChar, 50).Value = nomtxt.Text;
.....
See MSDN SqlParameterCollection.Add
and more info about the difference between Add and AddWithValue are explained here
How Data Access Code Affects Database Performance

Adding Data with Same Primary Key Data in ASP.Net

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..

Categories