Retreive last record inserted - c#

I want to retrieve the last record of data inserted. I researched and learn't I must use SELECT LAST_INSERT_ID(). I have tried and not working. So I have provided my code below
//Inserting into Student Table
string query = "INSERT INTO student(name) Values('" + txtboxname.Text + "' )";
// query= "SELECT LAST_INSERT_ID()";
// query += " SELECT SCOPE_IDENTITY()";
//Inserting into course table
string query1 = "INSERT INTO course(title) Values('" + txttitle.Text + "')";
// query1 = " SELECT LAST_INSERT_ID()";
//Execute Insert Statement queries
MySqlCommand command = new MySqlCommand(query, con);
command.ExecuteNonQuery();
command = new MySqlCommand(query1, con);
command.ExecuteNonQuery();
//Close and dispose off connections
command.Dispose();
con.Close();
//Preview page
string query1 = "SELECT (name) FROM student WHERE ID = id";
string query2 = "SELECT (title) FROM course WHERE ID = id";
MySqlCommand command = new MySqlCommand(query1, con);
lblname.Text = command.ExecuteScalar().ToString();
command = new MySqlCommand(query2, con);
lbltitle.Text = command.ExecuteScalar().ToString();
con.Close();

if you have set the table id to auto-increment then find the max id from the table that will be your last insert as per my knowledge if it works.

In your Code change as follows,
line no: 3 query="set #std_id=last_insert_id();"
line no: 7 query1="set #title_id=last_insert_id();"
Preview Page:
string query1 = "SELECT (name) FROM student WHERE ID = query";
string query2 = "SELECT (title) FROM course WHERE ID = query1";

Related

Why is select scope_identity() returning 1 for SQL query?

I am using SQL query to with SELECT SCOPE_IDENTITY() in sqlcommand. here is my code:
SqlCommand cmd = new SqlCommand("INSERT INTO tbl_Supplier(Supplier_Name,Supplier_Address, Supplier_PhoneNo,Supplier_City,Supplier_Remarks) VALUES('" + TextBox1.Text + "','" + TextBox2.Text + "','" + TextBox3.Text + "','"+DropDownList1.SelectedItem+"','"+TextBox4.Text+"') RETURN SCOPE_IDENTITY()", conn);
var id = cmd.ExecuteScalar();
conn.Close();
but the code is always returning 1?
You are using the wrong syntax to get that info.
"...; SELECT SCOPE_IDENTITY()"
(Notice also the semicolon before the SELECT and after the end of the first sql statement)
At this point the ExecuteScalar is able to get the first column of the first row returned by the SELECT
Said that, please take a bit of your time to learn how to execute "Parameterized Queries" your code is very weak and an easy target for Sql Injection
string cmdText = #"INSERT INTO tbl_Supplier
(Supplier_Name,
Supplier_Address,
Supplier_PhoneNo,
Supplier_City,
Supplier_Remarks)
VALUES(#name, #address, #phone, #city, #remarks);
SELECT SCOPE_IDENTITY()"
using(SqlCommand cmd = new SqlCommand(cmdText, connection))
{
connection.Open();
cmd.Parameters.Add("#name", SqlDbType.NVarWChar).Value = TextBox1.Text;
cmd.Parameters.Add("#address", SqlDbType.NVarWChar).Value = TextBox2.Text;
cmd.Parameters.Add("#phone", SqlDbType.NVarWChar).Value = TextBox3.Text;
cmd.Parameters.Add("#city", SqlDbType.NVarWChar).Value = DropDownList1.SelectedItem
cmd.Parameters.Add("#remarks", SqlDbType.NVarWChar).Value = TextBox4.Text;
var id = cmd.ExecuteScalar();
}
conn.Close();

Search record in ACCESS DATABASE using c#

i am trying to find the records based on the user input in msaccess database.
below is the code
string strProvider = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Employees.mdb";
string strSql = "SELECT * FROM tbl_employees where description like '" + txtsearch.Text.ToString() + "*'";
OleDbConnection con = new OleDbConnection(strProvider);
OleDbCommand cmd = new OleDbCommand(strSql, con);
con.Open();
cmd.CommandType = CommandType.Text;
OleDbDataReader dr = cmd.ExecuteReader();
int columnCount = dr.FieldCount;
When i ran the same query in my SQLView of msaccess i am getting records but when i ran it in VS i am not getting any records.
I think your matching should be changed:
String strSql = "SELECT * FROM tbl_employees WHERE description LIKE '" + txtsearch.Text.ToString() + "%'";
//Replaced * with %

How to retrieve a data from a table and insert into another table?

I am trying to retrieve "customer_id" from Customer table and insert it into
fare_tariff(tariff_id, customer_id, total_price)
So I retrieve the customer_id from Customer table as below:
using (SqlCommand command = new SqlCommand("SELECT customer_id FROM Customer WHERE UserName = '" + username + "' Password = '"+password +"' ", connection))
{
string cust_id = customer_id.ToString();
SqlDataReader myReader = command.ExecuteReader();
if (myReader.Read())
{
cust_id = myReader["customer_id"].ToString();
}
int c_id = Convert.ToInt32(cust_id);
myReader.Close();
custID(c_id);
}
and insert the customer_id into table fare_tariff like below:
using (SqlCommand command = new SqlCommand("INSERT INTO flight_reservation(tariff_id, customer_id, total_price) VALUES(#val1,#val2,#val3)", connection))
{
command.Parameters.Add("#val1", SqlDbType.Int).Value = tariff_id;
command.Parameters.Add("#val2", SqlDbType.Int).Value = customer_id;
command.Parameters.Add("#val3", SqlDbType.VarChar).Value = total_price.ToString();
command.ExecuteNonQuery();
}
I declared customer_id as a variable for storing customer_id.
Problem is : tariff_id and total_price inserted successfully but the column customer_id is null yet.
Help needed.
Fetching data to the client and returning row by row back to the server
can well produce big overhead. There's better way to do the same,
so called "insert/select" query:
using (SqlCommand command = connection.CreateCommand()) {
command.CommandText =
"insert into Flight_Reservation(\n" +
" Customer_Id,\n" +
" Tariff_Id,\n" +
" Total_Price)\n" +
" select Customer_Id,\n" +
" #prm_Tariff_Id,\n" +
" #prm_Total_Price\n" +
" from Customer\n" +
" where (UserName = #prm_UserName)\n" +
" (Password = #prm_Password)";
command.Parameters.Add("#prm_Tariff_Id", SqlDbType.VarChar, 80).Value = tariff_id;
command.Parameters.Add("#prm_Total_Price", SqlDbType.VarChar, 80).Value = total_price.ToString();
command.Parameters.Add("#prm_UserName", SqlDbType.VarChar, 80).Value = username;
command.Parameters.Add("#prm_Password", SqlDbType.VarChar, 80).Value = password;
command.ExecuteNonQuery();
}

Another shorten SQL string? c#

Some may already be noticing this and I would like to confirm it, I am really inexperienced with complex SQL strings. I only know simple SELECT , INSERT , UPDATE and DELETE statements. And to achieve my purpose I often use 2 SELECT statements, like this one :
con.Open();
string cmdstr = "SELECT UNIQUE FROM recipeList WHERE `stock_ID` = '" + stockIDTxtbox.Text + "'";
cmd = new MySqlCommand(cmdstr, con);
dr = cmd.ExecuteReader();
string menuID = "";
while (dr.Read())
{
menuID = (dr["menu_ID"].ToString());
}
dr.Close();
con.Close();
con.Open();
string cmdstr = "SELECT `menu_name` FROM recipedb WHERE `menu_ID` = '" + menuID + "'";
cmd = new MySqlCommand(cmdstr, con);
dr = cmd.ExecuteReader();
string menuName = "";
while (dr.Read())
{
menuName = (dr["menu_name"].ToString());
this.listView1.Items.Add(new ListViewItem(new string[]{ menuName }))
}
dr.Close();
con.Close();
Any ideas how to shorten this? o.O
You may write an SQL as:
string queryString = "SELECT r2.menu_name "+
"FROM recipelist rl "+
"INNER JOIN recipedb r2 "+
"ON rl.menu_ID = r2.menu_ID "+
"WHERE r1.stock_ID = '" + stockIDTxtbox.Text + "'";
Haven't written SQL in a while but it should be a join, so something like the following:
select rdb.menu_name
from recipedb rdb,
recipelist rl
where rl.menu_ID = rdb.menu_ID and
rl.stock_ID = * insert your stockIDTxtbox.Text in here without the stars *
Here is a short one:
con.Open();
string cmdstr = "SELECT menu_name FROM recipedb WHERE menu_ID in (SELECT UNIQUE menu_id from recipeList WHERE stock_ID = '" + stockIDTxtbox.Text + "')";
cmd = new MySqlCommand(cmdstr, con);
dr = cmd.ExecuteReader();
string menuName = "";
while (dr.Read())
{
menuName = (dr["menu_name"].ToString());
this.listView1.Items.Add(new ListViewItem(new string[]{ menuName }))
}
dr.Close();
con.Close();

Getting Data from Access into a text box in C# by clicking a button

I have a table in MS Access that contain: (FoodID, FoodName, Price).
In C# I have three text boxes (txtId, txtName, txtPrice) and a button (btnSearch).
My question is that, In C# I just type FoodID in (txtId) and then click on button Search It'll display FoodName and Price ( from table access) in txtName and txtPrice by itself. I got the source code from you but it error on (OleDbDataReader dr = cmd.ExecuteReader();) its message is "Data type mismatch in criteria expression" .
Please solve this problem for me. This is the whole source code that I got for you.
System.Data.OleDb.OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = "your connection string";
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = conn;
cmd.CommandText = "select FoodName, Price from tablename where FoodID = '" + txtId + "' ";
conn.Open();
OleDbDataReader dr = cmd.ExecuteReader();//error this line!
while(dr.Read())
{
txtName.Text = dr["FoodName"].ToString();
txtPrice.Text = dr["Price"].ToString();
}
dr.Close();
conn.Close();
I assume FoodID is int. You should remove single quotes in this case
cmd.CommandText = "select FoodName, Price from tablename where FoodID = " + txtId;
Even better - use parameters:
using (var connection = new OleDbConnection("your connection string"))
using (var command = connection.CreateCommand())
{
command.CommandText = "select FoodName, Price from tablename where FoodID = #FoodID";
command.Parameters.AddWithValue("FoodID", int.Parse(txtId.Text));
connection.Open();
var reader = command.ExecuteReader();
while (reader.Read())
{
txtName.Text = reader["FoodName"].ToString();
txtPrice.Text = reader["Price"].ToString();
}
}
I think the FoodId is of Integer type in the database but over here in the query you have passed as string so convert the string to integer.
cmd.CommandText = "select FoodName, Price from tablename where FoodID = '" + int.Parse(txtId.Text) + "' " ;
There seems to be no problem with this line of code :
OleDbDataReader dr = cmd.ExecuteReader();// correct way
I think the problem is in:
cmd.CommandText = "select FoodName, Price from tablename where FoodID = '" + txtId + "' ";
You need to use the .Text Propertie of the Textbox
cmd.CommandText = "select FoodName, Price from tablename where FoodID = '" + txtId.Text + "' ";

Categories

Resources