Get last ID from select query in C# WPF - c#

I would like to get last selected person ID.
string personID = "SELECT PersonID FROM TestDatabase.[dbo].[Persons] where name LIKE 'XYZ%'";
SqlCommand cmd = new SqlCommand(personID, con);
SqlDataReader reader = cmd.ExecuteReader();
var lastSelectedSingleClientPhoneId = reader.GetDecimal(0);
But unfortunately it did not work. I already tried to get int16, int32 and int64. When i use INSERT I can get the ID using the following select:
SELECT SCOPE_IDENTITY();
Insert command below:
string insertPerson = "INSERT INTO TestDatabase.[dbo].[Persons] (firstName,secondName) VALUES (#firstName,#secondName);SELECT SCOPE_IDENTITY();";
SqlCommand cmd = new SqlCommand(insertPerson, con);
cmd.Parameters.AddWithValue("#firstName", txt_firstName.Text);
cmd.Parameters.AddWithValue("#secondName", txt_secondName.Text);
SqlDataReader reader = cmd.ExecuteReader();
reader.Read();
var lastInsertedPersontId = reader.GetDecimal(0);'

This should return all Persons beginning with 'XYZ' in the Persons database table.
string personID = "SELECT PersonID FROM TestDatabase.[dbo].[Persons] where name LIKE 'XYZ%'";
using(var cmd = new SqlCommand(personID, con))
using (var reader = cmd.ExecuteReader())
{
while(reader.Read())
{
Console.WriteLine(reader.GetValue(0));
}
}
I appreciate you're looking for a type to call GetXXX, but you can easily extend this pseudo-code to determine the appropriate type.

You can try combining the two SQL statements as one CommandText value then use ExecuteScalar to return the last inserted ID
string insertPerson = "INSERT INTO TestDatabase.[dbo].[Persons] (firstName,secondName) VALUES (#firstName,#secondName); SELECT SCOPE_IDENTITY();";
SqlCommand cmd = new SqlCommand(insertPerson, con);
cmd.Parameters.AddWithValue("#firstName", txt_firstName.Text);
cmd.Parameters.AddWithValue("#secondName", txt_secondName.Text);
int personID = (int)cmd.ExecuteScalar();
/// ... convert integer value to a string or do something
You can also try this SQL statement as an alternative:
SELECT TOP 1 PersonID FROM Persons ORDER BY PersonID DESC;

Related

c# Inserting int value into SQL table

I want to insert some data into SQL table. But while inserting int no matter what I've tried I get error:
System.Data.SqlClient.SqlException: 'Conversion failed when converting
the varchar value '#ID' to data type int.'
I even manually set ID to 1 simply to be 100 % sure it's int but still get that error
String query = "INSERT INTO table(dbo.table.ID, dbo.table.secondvar)
VALUES ('#ID','#secondvar')";
using (SqlCommand cmd = new SqlCommand(query, connection))
{
int ID = 1;
cmd.Parameters.AddWithValue("#ID", ID);
cmd.Parameters.AddWithValue("#secondvar", tableModel.secondvar);
connection.Open();
int result = cmd.ExecuteNonQuery();
Remove the quotes around the values. The framework handles that already.
VALUES ('#ID','#secondvar')
should be
VALUES (#ID,#secondvar)
ID is an integer so it must not be between '':
Change this line:
String query = "INSERT INTO table(dbo.table.ID, dbo.table.secondvar)
VALUES ('#ID','#secondvar')";
to this:
String query = "INSERT INTO table(dbo.table.ID, dbo.table.secondvar)
VALUES (#ID,#secondvar)";
And its better avoid using AddWithValue instead use it like:
String query = "INSERT INTO table(dbo.table.ID, dbo.table.secondvar)
VALUES (#ID,'#secondvar')";
using (SqlCommand cmd = new SqlCommand(query, connection))
{
int ID = 1;
cmd.Parameters.Add("#ID", SqlDbType.Int).Value = ID;
cmd.Parameters.Add("#secondvar", SqlDbType.VarChar).Value = somevalue;
//rest of the code
}

How to store Id (primary key) of newly inserted row into a variable using C#

I am trying to get the Id of newly inserted row as below,
INSERT dbo.Users(Username)
OUTPUT inserted.ID
VALUES('my new name');
and when I execute this query in SQL Server 2008, it returns the id. My question is how to store this Id in a variable in asp.net C# to use this value further.
Note: I am not using parametrized query.
use the execuate scalar property for your command
int NewNameId = (int)sqlCommand.ExecuteScalar();
DECLARE #inserted TABLE ( id INT NOT NULL);
INSERT dbo.Users(Username)
OUTPUT inserted.ID INTO #inserted
VALUES('my new name');
SELECT (id)
FROM #inserted
not sure. just check
something like:
try
{
SqlConnection conn = new SqlConnection(connString);
SqlCommand cmd = null;
SqlDataReader rdr = null;
conn.Open();
cmd = new SqlCommand(sqlsel, conn);
rdr = cmd.ExecuteReader();
while (rdr.Read())
{
var _id = rdr.GetInt(0);
}
conn.Close();
// do something with _id

C# SQL query not returning anything

I have the public DataTable here and the code looks right, but its not returning anything, the OrderID is correct, the query itself is correct, its not returning anything...can anyone tell me why?
public DataTable get_OrderTransaction_Master_ByOrderID(Int64 orderID)
{
cn = new SqlConnection(objCommon.IpcConnectionString);
cn.Open();
string query = "select transactionID from dbo.OrderTransaction_Master where orderID = " + orderID;
SqlCommand queryCommand = new SqlCommand(query, cn);
SqlDataReader queryCommandReader = queryCommand.ExecuteReader();
DataTable dataTable = new DataTable();
dataTable.Load(queryCommandReader);
cn.Close();
return dataTable;
}
Caveat:This is a guess based on incomplete information:
Try this: Change query string and add the line to add the parameter.
string query = "select transactionID from dbo.OrderTransaction_Master where orderID = #OrderId";
SqlCommand queryCommand = new SqlCommand(query, cn);
queryCommand.Parameters.AddWithValue("#OrderId", orderID);
SqlDataReader queryCommandReader = queryCommand.ExecuteReader();
Explanation: Not only will this prevent SQL Injection, it will automatically assure that the OrderId is handled correctly.
You didn't specify what the data type is for the OrderId in the database. I'm guessing it may be non-numeric. (guid or varchar - I've seen databases that use nun-numeric IDs, so it's not inconceiveable.) If it's non-numeric you may be missing the quotes areound the value.
Example:
Where Id = 1
is NOT the same as
Where Id= '1'
Using a parameterized query will automagically fix this for you.

Get int value from command in c#

string sql = "Select UserId From User where UserName='Gheorghe'";
SqlCommand cmd=new SqlCommand(sql, connection);
cmd.ExecuteScalar(); //this statement return 0
but I want to get the id of user?
how can I get it?
You need the SqlDataReader.
SqlDataReader Provides a way of reading a forward-only stream of rows from a SQL Server database.
Sample
string sql = "Select UserId From User where UserName='Gheorghe'";
SqlCommand cmd=new SqlCommand(sql, connection);
SqlDataReader rd = cmd.ExecuteReader();
if (rd.HasRows) {
rd.Read(); // read first row
var userId = rd.GetInt32(0);
}
More Information
MSDN - SqlDataReader Class
Simply cast the returned value:
int userId = (Int32)cmd.ExecuteScalar();
But be aware that ExecuteScalar will return null if your query returns an empty result set, and in that case the above code snippet will throw an InvalidCastException.
try with select TOP 1 and ExecuteScalar
string sql = "Select TOP 1 UserId From User where UserName='Gheorghe'";
using (SqlConnection conn = new SqlConnection(connString))
{
conn.Open();
using(SqlCommand cmd = new SqlCommand(sql, conn))
{
var result = (Int32)cmd.ExecuteScalar();
}
}

How to retrive last enty in ACCESS database using C# via OleDB with sql commands

Again me with me form base program (with visual C# 2010)
After getting most of my program to work I started adding some small "extras"
Here is the problem: when I add a new item, I want to open a MessageBox and write the id of the new item.
Table = Item, field = item_id
Tried using:
cmd.CommandText = "SELECT LAST(item_id) FROM Item";
OleDbDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
id = dr["item_id"].ToString();
}
Here is the full function:
public void ItemInsert(string name,string creator,string publishing,string itemType,string genere, string year)
{
string id ="";
cmd.CommandText = "INSERT INTO Item (item_name, creator_name,publishing_name,item_type,genre,year_publication,location) VALUES (#item_name, #creator_name,#publishing_name,#item_type,#genre,#year_publication,#location);";
cmd.Parameters.AddWithValue("#item_name", name);
cmd.Parameters.AddWithValue("#creator_name", creator);
cmd.Parameters.AddWithValue("#publishing_name",publishing);
cmd.Parameters.AddWithValue("#item_type", itemType);
cmd.Parameters.AddWithValue("#genre",genere);
cmd.Parameters.AddWithValue("#year_publication",year);
cmd.Parameters.AddWithValue("#location", 0);//location=0 when in library
con.Open(); // open the connection
cmd.ExecuteNonQuery();
//get item id
cmd.CommandText = "SELECT LAST(item_id) FROM Item";
OleDbDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
id = dr["item_id"].ToString();
}
con.Close();
MessageBox.Show("Item ID : " + id+"","Added new item");
}
Replace:
cmd.CommandText = "SELECT LAST(item_id) FROM Item";
With:
cmd.CommandText = "SELECT ##IDENTITY";
In my case the "IDENTITY" stuff has not worked (maybe because the field was not PK or AI). It was always the id "0"
i used this query:
cmd.CommandText = "SELECT TOP 1 item_id FROM Item ORDER BY item_id DESC";
Note that the "TOP 1" is equal to other sql-dialect's "LIMIT 1"
so in short, without setting further cmd options:
object scalarInt = new OleDbCommand("SELECT TOP 1 item_id FROM Item ORDER BY item_id DESC", con).ExecuteScalar();
int lastItemId = (int?) scalarInt ?? 0;
where the 0 at the end of the last line is the default return value, if there are no entries yet. you may use 1 as database Id's typically start with 1.

Categories

Resources