Retrieve the last id from the SQL Server database table - c#

How do I get the last id created in the policy table and store it into a variable so that I can use it for another table called backupspec table.
System.Data.SqlClient.SqlConnection dataConnection = new SqlConnection();
dataConnection.ConnectionString =
#"Data Source=JAGMIT-PC\SQLEXPRESS;Initial Catalog=SumooHAgentDB;Integrated Security=True";
System.Data.SqlClient.SqlCommand dataCommand = new SqlCommand();
dataCommand.Connection = dataConnection;
//tell the compiler and database that we're using parameters (thus the #first, #last, #nick)
dataCommand.CommandText = ("Insert Policies ( PolicyName, PolicyDesc, TimeAdded,OSFlag, CreateVSSSnapshot, CreateAuditLogForRecoveries, AllowUsersToOverwriteFiles, AutoHandleEnvErrors, NotifyOnEnvErrorCount, NotifyOnFileFailure, NotifyOnFileFailureCount, NotifyOnLackOfPCContact, NotifyOnLackOfPCContactDays, NotifyOnRecoveryFailures, NotifyOnRecoveryFailureReason) values (#pn,#pd,#TimeAdded,#os,#vss,#al,#uow,#hee,#oeec,#off,#offc,#oloc,#olocd,#orf,#orfr)");
dataCommand.Parameters.AddWithValue("#pn",pn);
dataCommand.Parameters.AddWithValue("#pd",pd);
dataCommand.Parameters.AddWithValue("#TimeAdded",TimeAdded);
dataCommand.Parameters.AddWithValue("#os",os);
dataCommand.Parameters.AddWithValue("#vss",vss);
dataCommand.Parameters.AddWithValue("#al",al);
dataCommand.Parameters.AddWithValue("#uow",uow);
dataCommand.Parameters.AddWithValue("#hee",hee);
dataCommand.Parameters.AddWithValue("#oeec",oeec);
dataCommand.Parameters.AddWithValue("#off",off);
dataCommand.Parameters.AddWithValue("#offc",offc);
dataCommand.Parameters.AddWithValue("#oloc",oloc);
dataCommand.Parameters.AddWithValue("#olocd",olocd);
dataCommand.Parameters.AddWithValue("#orf",orf);
dataCommand.Parameters.AddWithValue("#orfr",orfr);
dataConnection.Open();
dataCommand.ExecuteNonquery();
dataConnection.Close();
ArrayList jaja = (ArrayList)Session["BackupSpecList"];
for (int i = 0; i < jaja.Count; i++)
{
BackupSpecEntry bsp = (BackupSpecEntry)jaja[i];
string path = bsp.path;
string inclExcl = bsp.inclExcl;
byte inclExclFlags = bsp.inclExclFlags;
bool indexContents = bsp.indexContents;
int serverBackupSpecId = bsp.serverBackupSpecId;
int freq = bsp.freq;
int retention = bsp.retention;
int policyID =DONT KNOW HOW TO GET THIS VALUE;
long specChangeTime = 0;
long backupTime = 0;
dataCommand.CommandText = ("Insert BackupSpec (PolicyID, Path, ServerBackupSpecID, Freq, Retention, InclExclFlags, InclExcl, IndexContents, SpecChangeTime, BackupTime) values (#policyID,#path,#serverBackupSpecId,#freq,#retention,#inclExclFlags,#inclExcl,#indexContents,#specChangeTime,#backupTime)");
dataCommand.Parameters.AddWithValue("#policyID", policyID);
dataCommand.Parameters.AddWithValue("#path", path);
dataCommand.Parameters.AddWithValue("#serverBackupSpecId", serverBackupSpecId);
dataCommand.Parameters.AddWithValue("#freq", freq);
dataCommand.Parameters.AddWithValue("#retention", retention);
dataCommand.Parameters.AddWithValue("#inclExclFlags", inclExclFlags);
dataCommand.Parameters.AddWithValue("#inclExcl", inclExcl);
dataCommand.Parameters.AddWithValue("#indexContents", indexContents);
dataCommand.Parameters.AddWithValue("#specChangeTime", specChangeTime);
dataCommand.Parameters.AddWithValue("#backupTime", backupTime);
dataConnection.Open();
dataCommand.ExecuteNonQuery();
dataConnection.Close();
}
I am getting error with the label id...
can some 1 help me with this..??
I am not getting the last policyID created after inserting please help...
Please help

Use scope_identity:
strSQL = "INSERT INTO Policies (...) VALUES (#vals....);SELECT #result = scope_identity()"
SQLCommand.CommandText = strSQL;
SQLCommand.Parameters.Add("#result", SqlDbType.Int);
SQLCommand.ExecuteScalar();
int id = SQLCommand.Parameters["#result"].Value;

You can use either SCOPE_IDENTITY or ##IDENTITY
SCOPE_IDENTITY:
strSQL = "INSERT INTO Policies (...) VALUES (#vals....);SELECT SCOPE_IDENTITY()";
SQLCommand.CommandText = strSQL;
IdReturned = SQLCommand.ExecuteScalar();
##IDENTITY:
strSQL = "INSERT INTO Policies (...) VALUES (#vals....);SELECT ##Identity";
SQLCommand.CommandText = strSQL;
IdReturned = SQLCommand.ExecuteScalar();
For the differences between the two i recommend reading this article

If you do a INSERT INTO Policies() call first, in order to get the lastid, you could do something like this:
int lastId = 0;
using(SqlConnection Connection = new SqlConnection("(connection string)"))
{
string queryStatement =
"INSERT INTO dbo.Policies(fields) OUTPUT Inserted.LastID VALUES(....)";
using(SqlCommand Command = new SqlCommand(queryStatement, Connection))
{
Connection.Open();
lastId = Command.ExecuteScalar();
Connection.Close();
}
}
Use the OUTPUT ....... clause to return the newly inserted lastId.
Then go on and use that value in your main query.
Marc

Related

Count how many users are added to database

I have some code which collect all users from Active Directory and INSERTs them into my database. After I have inserted all users which don't already exist in my database I want to count how many new users I added to the database.
So far want I create is this which is function to Execute store procedure
public void ExcStrPrc(string Username, string DisplayName, bool isEnable, bool PassNevExp)
{
SqlConnection conn = new SqlConnection(#"Data Source=(LocalDb)\MSSQLLocalDB;Initial Catalog=DesignSaoOsig1;Integrated Security=True");
SqlCommand cmd = new SqlCommand("ADProcTemp", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Username", Username.ToString().Trim());
cmd.Parameters.AddWithValue("#DisplayName", DisplayName.ToString().Trim());
cmd.Parameters.AddWithValue("#isEnabled", Convert.ToInt32(isEnable));
cmd.Parameters.AddWithValue("#PassNevExp", Convert.ToInt32(PassNevExp));
conn.Open();
int k = cmd.ExecuteNonQuery();
if (k != 0)
{
Console.WriteLine("Record Inserted Succesfully into the Database");
}
conn.Close();
}
And here is my main program
public static List<Korisnik> VratiKorisnike()
{
List<Korisnik> lstADUsers = new List<Korisnik>();
string sDomainName = "saostest";
string DomainPath = "LDAP://" + sDomainName;
string fileLoc = #"C:\output.txt";
DirectoryEntry searchRoot = new DirectoryEntry(DomainPath);
DirectorySearcher search = new DirectorySearcher(searchRoot);
search.Filter = "(&(objectClass=user)(objectCategory=person))";
search.PropertiesToLoad.Add("samaccountname"); // Username
search.PropertiesToLoad.Add("displayname"); // display name
search.PropertiesToLoad.Add("userAccountControl"); // isEnabled
search.PropertiesToLoad.Add("pwdLastSet"); //passwordExpires
DataTable resultsTable = new DataTable();
resultsTable.Columns.Add("samaccountname");
resultsTable.Columns.Add("displayname");
resultsTable.Columns.Add("Neaktivan");
resultsTable.Columns.Add("dontexpirepassword");
SearchResult result;
SearchResultCollection resultCol = search.FindAll();
if (resultCol != null)
{
for (int counter = 0; counter < resultCol.Count; counter++)
{
string UserNameEmailString = string.Empty;
result = resultCol[counter];
if (result.Properties.Contains("samaccountname")
&& result.Properties.Contains("displayname"))
{
int userAccountControl = Convert.ToInt32(result.Properties["userAccountControl"][0]);
string samAccountName = Convert.ToString(result.Properties["samAccountName"][0]);
int isEnable;
int Dont_Expire_Password;
if ((userAccountControl & 2) > 0)
{
isEnable = 0;
}
else
{
isEnable = 1;
}
if ((userAccountControl & 65536) > 0)
{
Dont_Expire_Password = 1;
}
else
{
Dont_Expire_Password = 0;
}
Korisnik korisnik = new Korisnik();
korisnik.Username = (result.Properties["samaccountname"][0]).ToString();
korisnik.DisplayName = result.Properties["displayname"][0].ToString();
korisnik.isEnabled = Convert.ToBoolean(result.Properties["userAccountControl"][0]);
DataRow dr = resultsTable.NewRow();
dr["samaccountname"] = korisnik.Username.ToString();
dr["displayname"] = korisnik.DisplayName.ToString();
dr["neaktivan"] = Math.Abs(isEnable);
dr["dontexpirepassword"] = Dont_Expire_Password;
resultsTable.Rows.Add(dr);
// Poziva se store procedura
Program p = new Program();
p.ExcStrPrc(korisnik.Username.ToString().Trim(), korisnik.DisplayName.ToString().Trim(), Convert.ToBoolean(isEnable), Convert.ToBoolean(Dont_Expire_Password));
//Ukupan broj dodanih novih usera
string connectionString = #"Data Source = (LocalDb)\MSSQLLocalDB; Initial Catalog = DesignSaoOsig1; Integrated Security = True";
System.Data.SqlClient.SqlConnection sqlConnection = new System.Data.SqlClient.SqlConnection(connectionString);
sqlConnection.Open();
System.Data.SqlClient.SqlCommand sqlCommand = new System.Data.SqlClient.SqlCommand("SELECT COUNT(*) FROM [dbo].[tblZaposleni_AD]");
sqlCommand.Connection = sqlConnection;
int RecordCount = Convert.ToInt32(sqlCommand.ExecuteScalar());
Console.WriteLine("Ukupan broj dodanih novi usera:", sqlCommand);
lstADUsers.Add(korisnik);
}
}
var json = JsonConvert.SerializeObject(resultCol, Formatting.Indented);
var res = json;
Console.WriteLine("Ispis uspjesno obavljen");
Console.ReadLine();
File.WriteAllText(fileLoc, json);
}
return lstADUsers;
}
}
}
Right here I add these logic
string connectionString = #"Data Source = (LocalDb)\MSSQLLocalDB; Initial Catalog = DesignSaoOsig1; Integrated Security = True";
System.Data.SqlClient.SqlConnection sqlConnection = new System.Data.SqlClient.SqlConnection(connectionString);
sqlConnection.Open();
System.Data.SqlClient.SqlCommand sqlCommand = new System.Data.SqlClient.SqlCommand("SELECT COUNT(*) FROM [dbo].[tblZaposleni_AD]");
sqlCommand.Connection = sqlConnection;
int RecordCount = Convert.ToInt32(sqlCommand.ExecuteScalar());
Console.WriteLine("Ukupan broj dodanih novi usera:", sqlCommand);
But here is problem which I didn't get any result (number)? Anyone how can help me to solve this problem?
Stored Procedure
CREATE PROCEDURE ADProcTemp
#Username varchar(250),
#DisplayName varchar(70),
#isEnabled tinyint,
#PassNevExp tinyint
AS
set nocount on
BEGIN
IF NOT EXISTS (SELECT TOP 1 PrezimeIme FROM [dbo].[tblZaposleni_AD] with (NOLOCK) WHERE NetworkLogin = #Username)
BEGIN
IF(#isEnabled = 1)
INSERT INTO [dbo].[tblZaposleni_AD](NetworkLogin,PrezimeIme,Status,PassNevExp)
VALUES (#Username, #DisplayName, #isEnabled,#PassNevExp)
END
ELSE
BEGIN
UPDATE [dbo].[tblZaposleni_AD]
SET Status = #isEnabled
WHERE NetworkLogin = #Username AND Status <> #isEnabled
END
END
First in your stored procedure you need to remove SET NOCOUNT ON in order to allow the sp to return the number of row affected.
Then in your c# code instead of
int RecordCount = Convert.ToInt32(sqlCommand.ExecuteScalar());
You need to call this
int RecordCount = Convert.ToInt32(sqlCommand.ExecuteNonQuery());
From the MSDN doc :
ExecuteScalar
Returns
Object
The first column of the first row in the result set, or a null reference (Nothing in Visual Basic) if the result set is empty. Returns a maximum of 2033 characters.
ExecuteNonQuery
Returns
Int32
The number of rows affected.

Record added two into the sqlserverdatabase using c#.net

i am creating a simple inventory system using c#. sales product table data added success.but sales table data added twice i don't know why. what i tried so far i attached below. i attached the sales table below record added twice
sales table
id subtoal pay bal
27 900.00 1000.00 100.00
28 900.00 1000.00 100.00
string bal = txtBal.Text;
string sub = txtSub.Text;
string pay = textBox1.Text;
sql = "insert into sales(subtoal,pay,bal) values(#subtoal,#pay,#bal); select ##identity;";
con.Open();
cmd = new SqlCommand(sql, con);
cmd.Parameters.AddWithValue("#subtoal", sub);
cmd.Parameters.AddWithValue("#pay", pay);
cmd.Parameters.AddWithValue("#bal", bal);
int lastinsertID = int.Parse(cmd.ExecuteScalar().ToString());
cmd.ExecuteNonQuery();
string proddname;
int price;
int qty;
int tot;
for (int row = 0; row < dataGridView1.Rows.Count; row++)
{
proddname = dataGridView1.Rows[row].Cells[0].Value.ToString();
price = int.Parse(dataGridView1.Rows[row].Cells[1].Value.ToString());
qty = int.Parse(dataGridView1.Rows[row].Cells[2].Value.ToString());
int total = int.Parse(dataGridView1.Rows[row].Cells[3].Value.ToString());
sql1 = "insert into sales_product(sales_id,prodname,price,qty,total) values(#sales_id,#prodname,#price,#qty,#total)";
cmd1 = new SqlCommand(sql1, con);
cmd1.Parameters.AddWithValue("#sales_id", lastinsertID);
cmd1.Parameters.AddWithValue("#prodname", proddname);
cmd1.Parameters.AddWithValue("#price", price);
cmd1.Parameters.AddWithValue("#qty", qty);
cmd1.Parameters.AddWithValue("#total", total);
cmd1.ExecuteNonQuery();
}
MessageBox.Show("Record Addddedddd");
con.Close();
As per Larnu's commment you were executing the query twice. In this case you should only use the ExecuteScalar() version to retrieve the last inserted id for later use
I also wanted to point out that the design intent is to initialize the parameters collection once, then re use it many times, executing each time. You should also put using statements to make your commands, more like this, and you should probably get into the habit of using SCOPE_IDENTITY() rather than ##identity:
using(var con = new SqlConnection(...)){
con.Open();
string bal = txtBal.Text;
string sub = txtSub.Text;
string pay = textBox1.Text;
sql = "insert into sales(subtoal,pay,bal) values(#subtoal,#pay,#bal); select scope_identity();";
int lastinsertId = 0;
using(var cmd = new SqlCommand(sql, con){
cmd.Parameters.AddWithValue("#subtoal", sub);
cmd.Parameters.AddWithValue("#pay", pay);
cmd.Parameters.AddWithValue("#bal", bal);
lastinsertID = (int)cmd.ExecuteScalar();
}
string proddname = "";
int price = 0;
int qty = 0;
int tot = 0;
sql1 = "insert into sales_product(sales_id,prodname,price,qty,total) values(#sales_id,#prodname,#price,#qty,#total)";
using(var cmd1 = new SqlCommand(sql1, con)){
cmd1.Parameters.AddWithValue("#sales_id", lastinsertID);
cmd1.Parameters.AddWithValue("#prodname", proddname);
cmd1.Parameters.AddWithValue("#price", price);
cmd1.Parameters.AddWithValue("#qty", qty);
cmd1.Parameters.AddWithValue("#total", total);
for (int row = 0; row < dataGridView1.Rows.Count; row++)
{
proddname = dataGridView1.Rows[row].Cells[0].Value.ToString();
price = int.Parse(dataGridView1.Rows[row].Cells[1].Value.ToString());
qty = int.Parse(dataGridView1.Rows[row].Cells[2].Value.ToString());
int total = int.Parse(dataGridView1.Rows[row].Cells[3].Value.ToString());
cmd1 = new SqlCommand(sql1, con);
cmd1.Parameters["#sales_id"].Value = lastinsertID;
cmd1.Parameters["#prodname"].Value = proddname;
cmd1.Parameters["#price"].Value = price;
cmd1.Parameters["#qty"].Value = qty;
cmd1.Parameters["#total"].Value = total;
cmd1.ExecuteNonQuery();
}
} //end using sqlcommand
}//end using sqlconnection - it will close as a result
MessageBox.Show("Record Addddedddd");
And then I also wanted to point out that your life could get a lot easier if you use Dapper. With dapper the code would look more like:
using(var connection = new SqlConnection(...))
sql = "insert into sales(subtoal,pay,bal) values(#subtoal,#pay,#bal); select scope_identity();";
var lastInsertId = connection.Query<int>(sql, new {
subtoal = txtSub.Text,
pay = textBox1.Text,
bal = txtBal.Text
}
).Single();
foreach(...)
}
It does all the parameter jiggling for you, runs the query, manages the connection ,returns a type casted int etc
Also if your datagridview is based on a DataTable (and even better a strongly typed datatable) you can use it in your foreach. Here's what a strongly typed table would look like:
using(...){
foreach(var ro in SalesProductTable){
sql = "insert into sales_product(sales_id,prodname,price,qty,total) values(#sales_id,#prodname,#price,#qty,#total)";
dapperConnection.Execute(sql, new { ro.sales_id, ro.prodname, ro.price, ro.qty, ro.total });
}
Yep, that's it; just 4 lines of code, and it's easier if your #param names match your column names in your strongly typed table.
I think you might even just be able to get Dapper to do the looping too, by passing the datatable in, so long as the rows have properties that are the same as the parameters in the query:
using(...){
sql = "insert into sales_product(sales_id,prodname,price,qty,total) values(#sales_id,#prodname,#price,#qty,#total)";
dapperConnection.Execute(sql, salesProductTable);
}
take a look - http://dapper-tutorial.net

How to apply formula on all values of one column in sql server in c#?

I am making payroll management system in which double pay salary is equal to some proportion of employee's fix pay.That proportion is given by some percentage i.e. 12% of fix pay and this percentage tends to change time by time. And when the percentage is changed then double pay value according to that percentage must also be changed in employee table.
here is my code:
string query;
query = "select count(*) from ConditionalEarnings where [Double Duty]!=0";
SqlCommand value = new SqlCommand(query,DataFind);
value.ExecuteNonQuery();
int no = Convert.ToInt32(value.ExecuteScalar());
textBox7.Text = no.ToString();
for (int o = 0; o< no; o++)
{
string query1;
query1 = "select EmpId from ConditionalEarnings where [Double Duty]!=0";
SqlCommand value1 = new SqlCommand(query1, DataFind);
value1.ExecuteNonQuery();
int id = Convert.ToInt32(value1.ExecuteScalar());
textBox8.Text = id.ToString();
string query2;
query2 = "Select EmpRunningBasic from EmployeeRunningBasic where EmpId=#id";
SqlCommand r = new SqlCommand(query2,DataFind);
r.Parameters.Add("#id", SqlDbType.VarChar).Value = id;
r.ExecuteNonQuery();
int rb = Convert.ToInt32(r.ExecuteScalar());
int doublechange = Convert.ToInt32(textBox1.Text);
int apply = (rb * doublechange)/100;
SqlCommand f = new SqlCommand("Update ConditionalEarnings set [Double Duty]='" + apply + "' where EmpId=#id", DataFind);
f.Parameters.Add("#id", SqlDbType.VarChar).Value = id;
f.ExecuteNonQuery();
}
And my form is as follow:
Its my form
This is my code to perform task.
When I enter percentage and execute program to update all values in that specific column of double pay, only 1st row of table is changed and all other row's cell for double duty remain unchanged. Means my program works in a loop and calculate and replace value of my first row's column again and again without going to the next row. How to apply change on all rows selected on base of same criteria?
its my table showing employee id column and double duty column highlighted
The value of double duty column is not changing for all employee ids but for only first id in table.
First you have to get the Employees (with their Running Basics) that you want to Iterate, then apply your calculation on every one then update your database
have a look at the below code , it may help you (modify the code to match your needs)
int no = 0;
string query = "select count(*) from ConditionalEarnings where [Double Duty]!=0";
using (SqlConnection conn = new SqlConnection(connString))
{
SqlCommand cmd = new SqlCommand(query, conn);
conn.Open();
no = Convert.ToInt32(cmd.ExecuteScalar());
}
string selectQuery = "select a.EmpId,b.EmpRunningBasic from ConditionalEarnings a left join EmployeeRunningBasic b on a.EmpId=b.EmpId where a.[Double Duty]!=0";
SqlDataAdapter adapter = new SqlDataAdapter(selectQuery, DataFind);
DataTable dtEmp;
adapter.Fill(dtEmp);
textBox7.Text = no.ToString();
string updateQuery = "";
foreach (DataRow row in dtEmp)
{
string empId = row["EmpId"].ToString();
textBox8.Text = empId;
int rb = Convert.ToInt32(row["EmpRunningBasic"]);
int doublechange = Convert.ToInt32(textBox1.Text);
int apply = (rb * doublechange) / 100;
updateQuery += string.Format("Update ConditionalEarnings set [Double Duty]='{1}' where EmpId='{0}';", empId, apply);
}
if (!string.IsNullOrEmpty(updateQuery))
{
using (SqlConnection conn = new SqlConnection(connString))
{
SqlCommand cmd = new SqlCommand(updateQuery, conn);
conn.Open();
cmd.ExecuteNonQuery();
}
}

How to find Max element in SQLite?

I need select the maximum ID of PolygonId column. I save my data like this
string sql = "create table Polygons (PolygonId int, PointId int, X double, Y double)";
// Выполнение нашей команды
using (SQLiteCommand command = new SQLiteCommand(sql, m_dbConnection))
{
command.ExecuteNonQuery();
}
int pointId = 1;
for (int i = 0; i < listOfCustomPolygons.Count; i++)
for (int j = 0; j < listOfCustomPolygons[i].listOfVertexes.Count; j++)
{
string strSQL =
string.Format("INSERT INTO Polygons (PolygonId,PointId,X,Y) Values ('{0}','{1}','{2}','{3}')",
i+1,pointId,listOfCustomPolygons[i].listOfVertexes[j].X,
listOfCustomPolygons[i].listOfVertexes[j].Y );
pointId++;
using (SQLiteCommand insertCommand = new SQLiteCommand(strSQL, m_dbConnection))
{
insertCommand.ExecuteNonQuery();
}
}
After this I want select the max value from table Polygons and column PolygonId, but I got an IndexOutOfRangeException. How a can solve this problem?
using (SQLiteConnection connection = new SQLiteConnection("Data Source=" + openFileDialog.FileName + ";Version=3;"))
{
connection.Open();
string selectMaxId = "Select Max(PolygonId) From Polygons";
string selectQuery = "Select * From Polygons";
SQLiteCommand selectMaxCmd = new SQLiteCommand(selectMaxId,connection);
SQLiteDataReader dataReader = selectMaxCmd.ExecuteReader();
int maxId = Convert.ToInt32(dataReader["Select Max(PolygonId) From Polygons"]); // This is don't work! Why?
I found out the solution! It should look like
string selectMaxId = "Select Max(PolygonId) From Polygons";
SQLiteCommand selectMaxCmd = new SQLiteCommand(selectMaxId,connection);
object val = selectMaxCmd.ExecuteScalar();
int maxId = int.Parse(val.ToString());
I hope it can help somebody who face with similar problem)
First of all don't create table every time you run your code :) But you probably know that
You type like this:
int maxId = Convert.ToInt32(dataReader["Select Max(PolygonId) From Polygons"]);
Try this:
string selectMaxId = "Select Max(PolygonId) From Polygons";
SQLiteCommand selectMaxCmd = new SQLiteCommand(selectMaxId,connection);
SQLiteDataReader dataReader = selectMaxCmd.ExecuteReader();
int maxID = -1;
while(dataReader.read())
{
maxID = (int)dataReader.GetValue(0);
}
//This Works for me in WPF C#:
int MaxNum=0;
sqliteCon.Open();
string Query = "SELECT MAX(Promo_No)FROM Promo_File";
SQLiteCommand createCommand = new SQLiteCommand(Query, sqliteCon);
SQLiteDataReader DR = createCommand.ExecuteReader();
while (DR.Read())
{
MaxNum = DR.GetInt16(0);
}
sqliteCon.Close();
I had the same problem!
You have to learn the difference method of SQLiteCommand.
1.SQLiteCommand.ExecuteReader(). Get a SqlDataReader.
2.SQLiteCommand.ExecuteScalar(). Get a single value from the database.
Microsoft Doc:
cmd.CommandText = "SELECT COUNT(*) FROM dbo.region";
Int32 count = (Int32) cmd.ExecuteScalar();

Oracle 12C:Return the record after insert values

I want to get the value to insert a table in C#,something like this:
begin
insert into bk_library(floor,section) values('foo2','bar')
returning id into :outid;
select *from bk_library where id=:outid;
end;
Unfortunately, I failed
error info: Kiss.Linq.Linq2Sql.Test.EntryPoint.TestInsertReturnId:
Oracle.DataAccess.Client.OracleException : ORA-06550: line 3, column
1: PLS-00428: an INTO clause is expected in this SELECT statement
[Test]
public void TestInsertReturnId()
{
int ret = 0;
string connstring = "Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=localhost)(PORT=1521)))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=pdborcl)));User Id=system;Password=****;";
string sql = #"insert into bk_library(floor,section) values('foo','bar') returning id into :outid";
sql = getSqlString();
using (DbConnection conn = new OracleConnection(connstring))
{
conn.Open();
DbCommand command = conn.CreateCommand();
command.CommandType = CommandType.Text;
command.CommandText = sql;
OracleParameter lastId = new OracleParameter(":outid", OracleDbType.Int32);
lastId.Direction = ParameterDirection.Output;
command.Parameters.Add(lastId);
ret = command.ExecuteNonQuery();
// this code work fine ,now I want to get the entire record
LogManager.GetLogger<EntryPoint>().Info("The new id ={0}", lastId.Value.ToString());
conn.Close();
}
Assert.AreNotEqual(ret, 0);
}
ParameterDirection should be ReturnValue
lastId.Direction = ParameterDirection.ReturnValue;
From < http://arjudba.blogspot.ch/2008/07/pls-00428-into-clause-is-expected-in.html?m=1>
You need to write SELECT * INTO some_variable FROM bk_library instead of SELECT * FROM bk_library because I assume you want to store the data retrieved somehow. Therefore you need to declare a new variable some_variable (I assume of type string) and modify your SELECT statement as above. The data from the statement will then be stored in your new variable.
Hope this helps

Categories

Resources