How to put the autoincrement value in textbox - c#

private void button1_Click(object sender, EventArgs e)
{
String path = "Data Source=LOCALHOST; Initial Catalog= system; username=root; password=''";
MySqlConnection sqlconn = new MySqlConnection(path); //communicator //constructors
MySqlCommand sqlcomm = new MySqlCommand();
sqlconn.Open();
sqlcomm.CommandType = CommandType.Text;
sqlcomm.Connection = sqlconn;
sqlcomm.CommandText = "INSERT INTO maica (Lastname) VALUES ('" + textBox2.Text + "')";
sqlcomm.ExecuteNonQuery();
sqlconn.Close();
MessageBox.Show("Record saved");
}
This is a code in the add button. In phpmyadmin, I checked the autoincrement box. Whenever I run the form, I left the textBox1 which is the ID empty and I input a name in textBox2 which is the Lastname. In phpmyadmin, the ID autoincrements. The textbox1 should have a value of 0001 before I click the add button then after I click the add button, the textBox1 should have 0002. How do I put the autoincrement value in textBox1?This is in winform c#. Sorry for the bad english TIA.

If your database has an ID column with AUTO_INCREMENT set, you do not need to pass a value for the ID into the SQL Insert Statement. You can simply do:
sqlcomm.CommandText = "INSERT INTO maica (Lastname) VALUES ('" + textBox2.Text + ')";
It is also better to use SqlCommand instead of string concatenation as it is protects against SQL Injection and also deals with Type and formatting issues.

That's the query you need to run together with the insert.
SELECT LAST_INSERT_ID();
Here's some code to get the ID, first declare a global String somewhere in the class like that
private String entryIdString;
then
public int insertGetEntryID()
{
String sqlquery = "INSERT INTO maica (Lastname) VALUES ('" + textBox2.Text + "'); SELECT LAST_INSERT_ID();";
SqlCommand command = new SqlCommand(sqlquery, sqlconn);
try
{
sqlconn.Open();
entryIdStr = command.ExecuteScalar().ToString();
return int.Parse(entryIdStr);
}
catch (Exception ex)
{
Console.WriteLine("Exception in DBHandler", ex);
return -1;
}
finally
{
sqlconn.Close();
}
}
This method returns an integer holding the last ID in your table. Now you just set the value to textBox1
textBox1.Text = "ID: " + getEntryID();
or if you want just the ID
textBox1.Text = "" + getEntryID();
I was also just about to tell you what Gideon said about you inserting an ID (when if it's set to autoincrement in the DB, you don't need to).

Related

Invalid object name 'Main' error when inserting into Database - C# (WebForms), MySql

I know plenty of people have these issues, and I've actually tried to implement some of the suggestions to my code, however I'm getting errors that just don't make sense to me. This is my first time implementing database calls to my code. Can someone please tell me what I'm doing wrong? The following error pops up: ERROR: Invalid object name 'Main'. This is actually triggered by my exception so at least something is working. Otherwise, I don't know what the issue is. On the DB end, I have (username VARCHAR, email VARCHAR and number NCHAR) Please see the code below
static string path = Path.GetFullPath(Environment.CurrentDirectory);
static string databaseName = "u_DB.mdf";
string connectionString = #"Data Source=(localdb)\MSSQLLocalDB;AttachDbFilename=" + path + #"\" + databaseName + "; Integrated Security=True;";
private void button1_Click(object sender, EventArgs e)
{
// string query = "INSERT INTO UserInfo '" + textBox1.Text + "' and password = '" + textBox2.Text + "'";
string query = "insert into Main ([username], [email], [number]) values(#username,#email,#number)";
using (SqlConnection con = new SqlConnection(connectionString))
{
try
{
con.Open();
using (SqlCommand cmd = new SqlCommand(query, con))
{
cmd.Parameters.Add("#username", SqlDbType.VarChar).Value = textBox3.Text;
cmd.Parameters.Add("#email", SqlDbType.VarChar).Value = textBox2.Text;
cmd.Parameters.AddWithValue("#number", SqlDbType.VarChar).Value = textBox1.Text;
int rowsAdded = cmd.ExecuteNonQuery();
if (rowsAdded > 0)
MessageBox.Show("Added to Database");
else
MessageBox.Show("Nothing was added");
}
}
catch (Exception ex)
{
MessageBox.Show("ERROR: " + ex.Message);
}
con.Close();
}
}
Firstly, as Chetan assumed, do you have a main table?
The syntax of the query you are using is :
INSERT INTO table_name (column1, column2, column3, ...)
VALUES (value1, value2, value3, ...);
Furthermore,
AddWithValue(string parameterName, object value (<== The actual value to insert!));
in your case
AddWithValue("#number", textBox1.Text);
is enough.

insert,update in single button clickin winforms

I am not getting, how to do insert and update of the data in C# WinForms on single button click.
private void save_Click(object sender, EventArgs e)
{
SqlConnection cn = new SqlConnection();
cn.ConnectionString = "data source=Sai;database=kaur; user id=sa;password=azxc;";
cn.Open();
string gen;
if (radioButton1.Checked == true)
gen = "Male";
else
gen = "Female";
string clas = null;
clas = comboBox1.Text;
string section = null;
section = comboBox2.Text;
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "insert into studetail values('" + textBox1.Text + "','" + textBox2.Text + "','" + gen + "','" + textBox3.Text + "','" + clas + "','" + section + "')";
cmd.Connection = cn;
int n = cmd.ExecuteNonQuery();
if (n > 0)
MessageBox.Show(n + " Row Inserted.");
else
MessageBox.Show("Insertion failed.");
SqlDataAdapter da = new SqlDataAdapter("select * from studetail ", cn);
DataTable dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource = dt;
You can add a deletion before the insertion:
private void save_Click(object sender, EventArgs e)
{
DeletePerson(id); // add this
SqlConnection cn = new SqlConnection();
...
}
public void DeletePerson(int id)
{
using(SqlConnection connection = new SqlConnection(credentials))
{
connection.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = connection;
cmd.CommandText = "delete from studetail where someUniqeIdColumn = " + id;
cmd.ExecuteNonQuery();
}
}
Using responsible to dispose the connection.
Consider using Entity Framework or LINQ to SQL.
You are exposed to SQL injection.
First off the SQL query isn't quite right. It should look something like the following:
INSERT INTO studetail (columnName1, columnName2, ...columnNameN)
VALUES (value1, value2, ...valueN);
Where the column names are the columns where you want data to be inserted, and the values are the data you want inserted into said columns.
You should also be disposing the connection by wrapping the connection within a using statement.
using(var con = new SqlConnection(connectionString))
{
con.Open();
//rest of code that needs a connection here
}
Additionally, you need to be wary of SQL injection. I highly suggest reading this example from the MSDN website. It will give you an example of using an SQL Update and avoiding SQL injection with use of SqlCommand.Paramaters property.
You should also have a Primary Key in your database tables, if you don't already, so you can uniquely identify each record in a table.
To do an update and a save on the same button, you will need to check if a row already exists for the data that is being edited. This when a Primary comes in handy. You will want to check your database to see if a record already exists
SELECT 1 FROM studetail WHERE <Condition>
The WHERE condition will be the way you uniquely identify (a Primary Key) a row in your table. If the rows in the table are uniquely identified, the above SQL statement will return 1 if a value exists, which means you can UPDATE or 0 if no record exists, so you can INSERT

How do I code for an insert with a foreign key?

I have a Q and A page on my website where it displays a question pulled from a question table in my database. Below the question are two text boxes - one for the person's name and another for their answer, which is to be inserted into the answer table. The answer table has a FK questionID on it and that is where I am stuck. How do I write the script for the answer table in my code so it uses that questionID from the question table?
This is what I have so far:
protected void btnSubmitAnswer_onClick(object sender, EventArgs e)
{
String connectionString = "Server=root;Database=test;User=name;Password=test;";
using (SqlConnection conn = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand("INSERT INTO Answers (QuestionID, Answer_Name, Answer)" +
"VALUES (%%, '" + txtName.Text + "', '" + txtAnswer.Text + "')");
cmd.Connection = conn;
conn.Open();
cmd.ExecuteScalar().ToString();
}
}
The %% is what I need fixed. I was thinking about using a String variable but then I still don't know what I should use for that data type.
When you fetch the Question Id, you should store it into a variable in order to reuse it when inserting the command.
Like:
SELECT Id, /*And anything else you need*/ FROM QUESTION
And store it in a variable like Int32 QuestionId;
Also, for the sake of completeness, never concatenate SQL Strings, it makes your code vulnerable, instead use sql parameters.
protected void btnSubmitAnswer_onClick(object sender, EventArgs e)
{
String connectionString = "Server=root;Database=test;User=name;Password=test;";
using (SqlConnection conn = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand(
"INSERT INTO Answers (QuestionID, Answer_Name, Answer)" +
"VALUES (#prmQuestionId, #prmAnswerName, #prmAnswer)");
cmd.Parameters.Add(new SqlParameter("#prmQuestionId", QuestionId/*HERE INSERT THE ID VALUE OF THE FETCHED QUESTION*/));
cmd.Parameters.Add(new SqlParameter("#prmAnswerName", txtName.Text));
cmd.Parameters.Add(new SqlParameter("#prmAnswer", txtAnswer.Text));
cmd.Connection = conn;
conn.Open();
cmd.ExecuteScalar().ToString();
}
}
You will need to either store the id of the question in a hidden field and reference that else use an inner select within your insert statement to retrive the ID of the question.
The hidden field would be set up as below:
<input type="hidden" id="questionId" value="questionId" />
and then:
SqlCommand cmd = new SqlCommand("INSERT INTO Answers (QuestionID, Answer_Name, Answer)" +
"VALUES (questionId.Value, '" + txtName.Text + "', '" + txtAnswer.Text + "')");
The inner select would be in the form of
insert into table ((select id from questiontable where question = [the question text]), 'name', 'answer')
You need to do a get Query (Select Statement) to from the question table to retrieve the Question Id and then do an insert.
Also, use parameter strings, don't concatenate, your code can be injected with malicious behavior possibly deleting your database tables!
You need to create an int QuestionID variable to hold the current QuestionID. Just change it when the user changes questions. You could store this in Session.
Side note: I recommend parameterizing txtName.Text and txtAnswer.Text to avoid SQL injection.
At the time you are getting the question for the database get the Id as well and store it somewhere.
On a side note your code is open to SQL Injection. Use parameters instead to store the values from your textboxes like this:
SqlParameter param = new SqlParameter("#Name", SqlDbType.VarChar);
param.Value = txtName.Text;
cmd.Parameters.Add(param);
So your control is Gridview, this may be the case.. Try it.
protected void myRowCommand(object sender, GridViewCommandEventArgs e)
{
String connectionString = "Server=root;Database=test;User=name;Password=test;";
GridViewRow row = this.GridView1.SelectedRow;
int EntryID = row.RowIndex;
using (SqlConnection conn = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand("INSERT INTO Answers (QuestionID, Answer_Name, Answer)" +
"VALUES (EntryID, '" + txtName.Text + "', '" + txtAnswer.Text + "')");
cmd.Connection = conn;
conn.Open();
cmd.ExecuteScalar().ToString();
}
}
}

update data in access database using name two column

update data in access database using name two column
because one column have same data because SerialNumber and Start can be Repeat
that's make update in all row have same data
i use this code but i have syntax Error
private void button3_Click(object sender, EventArgs e)
{
try
{
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
string query = "update Timer set Stop='" + label1.Text + "'where (SerialNumber,Start)='" + comboBox1.Text + "','" + textBox1.Text + "' ";
command.CommandText = query;
command.ExecuteNonQuery();
MessageBox.Show("Data saved");
connection.Close();
send_data f2 = new send_data(comboBox1.Text,label2.Text);
f2.ShowDialog();
}
catch (Exception ex)
{
MessageBox.Show("ERORR" + ex);
}
}
The correct syntax for the WHERE clause is
WHERE fieldname operator value AND/OR fieldname operator value ....
So the correct way to update that record is
string query = #"update Timer set Stop=? where SerialNumber = ? AND Start = ?";
command.CommandText = query;
command.Parameters.AddWithValue("#p1", label1.Text);
command.Parameters.AddWithValue("#p2", comboBox1.Text );
command.Parameters.AddWithValue("#p3", textBox1.Text);
command.ExecuteNonQuery();
Notice that before the WHERE keyword you need a space and I have changed your code to use a more secure parameterized approach instead of string concatenation

C# Sql Column name is not valid

private void button4_Click_1(object sender, EventArgs e)
{
string s = textBox1.Text;
string s1 = comboBox1.Text;
string s2 = comboBox2.Text;
SqlCeConnection conn = new SqlCeConnection(#"Data Source=D:\Desktop\DB2\DB2\Database1.sdf");
try
{
conn.Open();
SqlCeCommand cmd = new SqlCeCommand(" update Kambariai set Klientas=[s] Where [Kambario rūšis]=[s1] ", conn);
cmd.ExecuteNonQuery();
toolStripStatusLabel1.Text = "Duomenys įrašyti";
conn.Close();
}
catch (Exception ee)
{
MessageBox.Show(ee.Message);
}
}
I am trying to update my datatable by updating Klientas value with textbox1.Text which is made to string = s. It should work fine as Sql But I get an error saying that The column name is not valid Column = s1. s1 shouldn't be targeted as column name it should be used as column row value.
This is outdated image Kliento ID is changed to Klientas
Try this:
SqlCeCommand cmd = new SqlCeCommand("update Kambariai set Klientas="+s+" Where [Kambario rūšis]='"+s1+"' ", conn);
Analysis:
From what you have tried, cmd has value like :
update Kambariai set Klientas=s Where [Kambario rūšis]=s1
From by putting proper double and single quotes around it, the value would be like:
update Kambariai set Klientas=1 Where [Kambario rūšis]='bar'
Side Note:
I would not recommend this method since it increases the risk of SQL injection. Use parameterized query instead.
Try This :
SqlCeCommand cmd = new SqlCeCommand(" update Kambariai set Klientas='" + s +"' Where [Kambario rūšis]='" + s1 + "'", conn);

Categories