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();
Related
Can anyone help improve performance? Updating the table takes a lot of time.
I am updating the serial number from datagridview to a table called dbo.json
// UPDATE dbo.json with numbers
private void BtnUpdateSql_Click(object sender, EventArgs e)
{
string VAL1;
string VAL2;
foreach (DataGridViewRow row in DgvWhistlSorted.Rows)
if (string.IsNullOrEmpty(row.Cells[5].Value as string))
{
}
else
{
for (int i = 0; i <= DgvWhistlSorted.Rows.Count - 2; i++)
{
VAL1 = DgvWhistlSorted.Rows[i].Cells[6].Value.ToString();
VAL2 = DgvWhistlSorted.Rows[i].Cells[0].Value.ToString();
var cnn = ConfigurationManager.ConnectionStrings["sql"].ConnectionString;
using (var con = new SqlConnection(cnn))
{
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "UPDATE dbo.json SET RowN = #VAL1 WHERE [A-order] = #VAL2";
cmd.Parameters.AddWithValue("#VAL1", VAL1);
cmd.Parameters.AddWithValue("#VAL2", VAL2);
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
}
MessageBox.Show("dbo.json is ready");
}
You shouldn't create the connection and command inside such a tight loop - create and open the connection and command ONCE before the loop, and in the loop, only set the parameter values and execute the query for each entry.
Something like this:
// UPDATE dbo.json with numbers
private void BtnUpdateSql_Click(object sender, EventArgs e)
{
string VAL1;
string VAL2;
// define connection string, query text *ONCE* before the loop
string cnn = ConfigurationManager.ConnectionStrings["sql"].ConnectionString;
string updateQuery = "UPDATE dbo.json SET RowN = #VAL1 WHERE [A-order] = #VAL2;";
// create connection and command *ONCE*
using (SqlConnection con = new SqlConnection(cnn))
using (SqlCommand cmd = new SqlCommand(updateQuery, cnn))
{
// Define parameters - adapt as needed (don't know the actual datatype they have)
cmd.Parameters.Add("#VAL1", SqlDbType.VarChar, 100);
cmd.Parameters.Add("#VAL2", SqlDbType.VarChar, 100);
// open connection ONCE, for all updates
con.Open();
foreach (DataGridViewRow row in DgvWhistlSorted.Rows)
{
if (!string.IsNullOrEmpty(row.Cells[5].Value as string))
{
for (int i = 0; i <= DgvWhistlSorted.Rows.Count - 2; i++)
{
VAL1 = DgvWhistlSorted.Rows[i].Cells[6].Value.ToString();
VAL2 = DgvWhistlSorted.Rows[i].Cells[0].Value.ToString();
// set the values
cmd.Parameters["#VAL1"].Value = VAL1;
cmd.Parameters["#VAL2"].Value = VAL2;
// execute query
cmd.ExecuteNonQuery();
}
}
}
// close connection after all updates are done
con.Close();
}
MessageBox.Show("dbo.json is ready");
}
Create the connection ONCE...you're creating a new database connection each time through the loop! And in fact you do not need to create new command objects each time. You can reuse the command object because the parameters are the same. Just clear the params each time through the loop.
Also don't do the grid view count in the loop, set a variable for it.
string query = "UPDATE dbo.json SET RowN = #VAL1 WHERE [A-order] = #VAL2";
int counter = DgvWhistlSorted.Rows.Count - 2;
using (SqlConnection con = new SqlConnection(cnn))
{
con.Open();
using(SqlCommand cmd = new SqlCommand(cnn,query))
{
cmd.Parameters.Clear();
//Do your loop in here
for (int i = 0; i <= counter; i++)
{
VAL1 = DgvWhistlSorted.Rows[i].Cells[6].Value.ToString();
VAL2 = DgvWhistlSorted.Rows[i].Cells[0].Value.ToString();
cmd.Parameters.AddWithValue("#VAL1", VAL1);
cmd.Parameters.AddWithValue("#VAL2", VAL2);
cmd.ExecuteNonQuery();
}
}
}
A better idea is to do this in one command, by passing all the data in a Table-Value Parameter (TVP):
First create the table type. I don't know your data types, so I'm guessing here. Make sure to match the types to the existing table.
CREATE TYPE dbo.OrderJson (
Order int PRIMARY KEY,
RowN nvarchar(max) NOT NULL
);
Then you can pass the whole thing in one batch. You need to create a DataTable to pass as the parameter, or you can use an existing datatable.
// UPDATE dbo.json with numbers
private void BtnUpdateSql_Click(object sender, EventArgs e)
{
var table = new DataTable {
Columns = {
{ "Order", typeof(int) },
{ "RowN", typeof(string) },
},
};
foreach (DataGridViewRow row in DgvWhistlSorted.Rows)
if (!string.IsNullOrEmpty(row.Cells[5].Value as string))
table.Rows.Add(DgvWhistlSorted.Rows[i].Cells[0].Value, DgvWhistlSorted.Rows[i].Cells[6].Value)
const string query = #"
UPDATE dbo.json
SET RowN = t.RowN
FROM dbo.json j
JOIN #tmp t ON t.order = j.[A-order];
";
using (var con = new SqlConnection(ConfigurationManager.ConnectionStrings["sql"].ConnectionString))
using (var cmd = new SqlCommand(query, con))
{
cmd.Parameters.Add(new SqlParameter("#tmp", SqlDbType.Structured) { Value = table, TypeName = "dbo.OrderJson" });
con.Open();
cmd.ExecuteNonQuery();
}
MessageBox.Show("dbo.json is ready");
}
I found that the fastest way would be to save the DATAGRIDVIEW to an SQL table and continue the process with - stored procedure + update query - between two tables - now it flies ...
Thank you all
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
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();
}
}
Hello guys I am trying to do some stuff while reading. What I am trying to do is edit row which was just read. But I get error. Maybe u have some suggestions how should I fix it, to make it work without quitting the data reader. P.S: Ignore that, that queries are open for SQL injections .
string select = "Select * FROM ivykiai WHERE `Ivikio diena` MOD Periodiskumas_d = 0 AND `Ivikio diena` > 0 AND `Ivikio diena` < `Dif dien`";
MySqlCommand command = new MySqlCommand(select, cnn);
MySqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
db1 = (now - Convert.ToDateTime(reader["Nuo"])).TotalDays;
MessageBox.Show(db1.ToString());
db1 = db1 - Convert.ToInt32(reader["Ivikio diena"]);
MessageBox.Show(db1.ToString());
b = Convert.ToInt32(db1) / Convert.ToInt32(reader["Periodiskumas_d"]);
MessageBox.Show(b.ToString());
a =+ Convert.ToInt32(reader["Suma"]);
MessageBox.Show(a.ToString());
a = a * b;
MessageBox.Show(a.ToString());
string prideti = "Update Lesos Set Grynieji=Grynieji + '"+ a +"'";
MySqlCommand prideti_cmd = new MySqlCommand(prideti, cnn);
string p = prideti_cmd.ExecuteNonQuery().ToString();
string update = "UPDATE Ivikiai Set `Ivykio diena`+= '" + db1 + "'";
MySqlCommand update_cmd = new MySqlCommand(update, cnn);
string u = update_cmd.ExecuteNonQuery().ToString();
}
reader.Close();
cnn.Close();
You can't execute prideti_cmd and update_cmd using the same connection inside the while (reader.Read()) block and reader is still open, however you can do that outside the while (reader.Read()) block and after closing reader. I would suggest creating the following class
public class MyClass
{
public DateTime Nuo { get; set; }
public int IvikioDiena { get; set; }
public int Periodiskumas_d { get; set; }
public int Suma { get; set; }
}
and change your code as below
string select = "Select * FROM ivykiai WHERE `Ivikio diena` MOD Periodiskumas_d = 0 AND `Ivikio diena` > 0 AND `Ivikio diena` < `Dif dien`";
using (MySqlCommand command = new MySqlCommand(select, cnn))
{
// execute the select query and store the results to list variable
List<MyClass> list = new List<MyClass>();
using (MySqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
MyClass record = new MyClass();
record.Nuo = Convert.ToDateTime(reader["Nuo"]);
record.IvikioDiena = Convert.ToInt32(reader["Ivikio diena"]);
record.Periodiskumas_d = Convert.ToInt32(reader["Periodiskumas_d"]);
record.Suma = Convert.ToInt32(reader["Suma"]);
list.Add(record);
}
}
// enumerate list and execute both the update queries
foreach (var record in list)
{
db1 = (now - record.Nuo).TotalDays;
MessageBox.Show(db1.ToString());
db1 = db1 - record.IvikioDiena;
MessageBox.Show(db1.ToString());
b = Convert.ToInt32(db1) / record.Periodiskumas_d;
MessageBox.Show(b.ToString());
a =+ record.Suma;
MessageBox.Show(a.ToString());
a = a * b;
MessageBox.Show(a.ToString());
string prideti = "Update Lesos Set Grynieji=Grynieji + '"+ a +"'";
MySqlCommand prideti_cmd = new MySqlCommand(prideti, cnn);
string p = prideti_cmd.ExecuteNonQuery().ToString();
string update = "UPDATE Ivikiai Set `Ivykio diena`+= '" + db1 + "'";
MySqlCommand update_cmd = new MySqlCommand(update, cnn);
string u = update_cmd.ExecuteNonQuery().ToString();
}
}
Generally you can ever only have one active command - SQL Server MARS being a little exceptiohn.
So, you can not use a connection WHILE IT HAS AN OPEN READER. Your first need to finish reading, then can update- or use anothe connection, which will get you into transaction isolation troubles.
Try this:
using (MySqlConnection cnn = new MySqlConnection(dbConnectionString))
{
cnn.Open();
MySqlCommand command = new MySqlCommand(select, cnn);
using (MySqlDataReader reader = command.ExecuteReader())
{
db1 = (now - Convert.ToDateTime(reader["Nuo"])).TotalDays;
MessageBox.Show(db1.ToString());
db1 = db1 - Convert.ToInt32(reader["Ivikio diena"]);
MessageBox.Show(db1.ToString());
b = Convert.ToInt32(db1) / Convert.ToInt32(reader["Periodiskumas_d"]);
MessageBox.Show(b.ToString());
a = +Convert.ToInt32(reader["Suma"]);
MessageBox.Show(a.ToString());
a = a * b;
MessageBox.Show(a.ToString());
}
string prideti = "Update Lesos Set Grynieji=Grynieji + '" + a + "'";
MySqlCommand prideti_cmd = new MySqlCommand(prideti, cnn);
string p = prideti_cmd.ExecuteNonQuery().ToString();
string update = "UPDATE Ivikiai Set `Ivykio diena`+= '" + db1 + "'";
MySqlCommand update_cmd = new MySqlCommand(update, cnn);
string u = update_cmd.ExecuteNonQuery().ToString();
}
All of the variables needed for the ExecuteNonQuery() are set when the data is read so you can use them outside the MySqlDataReader.ExecuteReader() function.
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