SQL update command in c# - c#

I have a SQL Server table with columns like this:
Mobile No <> OTP <> GenTime <> AuthTime <> IsAuth
9632587410 <> 256389 <> ****** <> ******** <> False
9876543210 <> 258963 <> ***** <> ****** <> False
so on ...
using (SqlConnection conn = new SqlConnection())
{
string inputn = Console.ReadLine();
long mobileNo;
long.TryParse(inputn, out mobileNo);
string inputo = Console.ReadLine();
int OTP;
Int32.TryParse(inputo, out OTP);
DateTime now = DateTime.Now;
conn.ConnectionString = "Data Source=10.0.0.98;Initial Catalog=TeletextCMS_Dev;User ID=Testteam;Password=Cognigent33#";
conn.Open();
//long r = 8947052876;
SqlCommand command = new SqlCommand("SELECT * FROM CustomerAuthOTP WHERE MobileNum=" + mobileNo, conn);
int f = 0;
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
//int OTP = reader[1];
int OTPGen = int.Parse(string.Format("{0}", reader[1]));
int a = now.Hour;
int b = now.Minute;
int e = now.Day;
DateTime then = DateTime.Parse(string.Format("{0}", reader[2]));
int c = then.Hour;
int d = then.Minute;
int g = then.Day;
if (e == g)
{
int t = (a - c) * 60 + b - d;
if (OTP == OTPGen && e == g && t <= 15)
{
Console.WriteLine("Hi");
f = 1;
}
else
{
Console.WriteLine("No");
}
}
if (e > g)
{
int t = (a + 24 - c) * 60 + b - d;
if (OTP == OTPGen && e == g && t <= 15)
{
Console.WriteLine("Hi");
f = 1;
}
else
{
Console.WriteLine("No");
}
}
}
}
if(f == 1)
{
SqlCommand cmd = new SqlCommand("UPDATE CustomerAuthOTP SET IsAuthenticated=True, AuthenticationTime=" + now, conn);
Console.WriteLine("Hi");
}
}
Now at the bottom I have an Update command. I tried to execute it but it is not doing anything.
There is no error in the code. Kindly some one help me out if f== 1 then in the CustomerAuthOTP table update the IsAuthenticated value to be true and also set the authentication time to now.DateTime()

First of all you should execute your commnd:
SqlCommand cmd = new SqlCommand("UPDATE CustomerAuthOTP SET IsAuthenticated=True, AuthenticationTime=" + now, conn);
cmd.ExecuteNonQuery();
I recommend to use SqlCommand.Parameters
var commandText = "UPDATE CustomerAuthOTP SET IsAuthenticated=#IsAuthenticated, AuthenticationTime=#AuthenticationTime";
SqlCommand cmd = new SqlCommand(commandText, conn);
cmd.Parameters.AddWithValue("#IsAuthenticated", true);
cmd.Parameters.AddWithValue("#AuthenticationTime", now);
cmd.ExecuteNonQuery();
It'll help SQL provider to determine parameter types and protects against SQL-injections.

DateTime now = DateTime.Now;
...
SqlCommand cmd = new SqlCommand(
"UPDATE CustomerAuthOTP SET IsAuthenticated=True, AuthenticationTime="
+ now, conn);
Note that this will be a string concatenation, and (depending on your locale, etc), the following is not valid TSQL:
UPDATE CustomerAuthOTP SET IsAuthenticated=True, AuthenticationTime=08/12/2015 12:08:32
The immediate problem is formatting (both the datetime and the boolean are wrong), but it is best fixed by parameterization - you should almost never be concatenating values into TSQL:
SqlCommand cmd = new SqlCommand(
"UPDATE CustomerAuthOTP SET IsAuthenticated=1, AuthenticationTime=#now", conn);
cmd.Parameters.AddWithValue("now", now);
cmd.ExecuteNonQuery();
Or with a tool like "dapper":
conn.Execute("UPDATE CustomerAuthOTP SET IsAuthenticated=1, AuthenticationTime=#now",
new { now });

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.

C# 'dbConn.ServerVersion' threw an exception of type 'System.InvalidOperationException'

Have the error 'dbConn.ServerVersion' threw an exception of type 'System.InvalidOperationException, however VisualStudio does not pause the program and throw the exception at me. Here is the code:private void BTN_NA_Click(object sender, EventArgs e)
{
if (TXT_NAUN.Text != "" && TXT_NAPW.Text != "" && TXT_NAPW2.Text != "")
{
if (TXT_NAPW.Text == TXT_NAPW2.Text)
{
string input = TXT_NAPW.Text;
int hash = 0;
int output = 0;
foreach (char chara in input)
{
int temp = 0;
temp = System.Convert.ToInt32(chara);
output = output + temp;
output = output * 2;
}
hash = output % 1000;
OleDbConnection dbConn = new System.Data.OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=BHShooterProjectDB.accdb");
string sql = "SELECT Accounts.PlayerID FROM Accounts ORDER BY Accounts.PlayerID DESC ";
///string comm = "SELECT Accounts.PlayerID from Accounts";
/// INNER JOIN Leaderboard ON Leaderboard.PlayerID = Accounts.PlayerID WHERE Accounts.PlayerUsername = #ip";
OleDbCommand cmd = new OleDbCommand(sql, dbConn);
string result = "";
dbConn.Open();
OleDbDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
result = reader[0].ToString();
}
dbConn.Close();
{
string comm = "INSERT INTO Accounts (PlayerUsername, PlayerPassword, PlayerID, PlayerInvID) VALUES (#NAUN, #HPW, #NAPI, #NAPI)";
OleDbCommand command = new OleDbCommand(comm, dbConn);
command.Parameters.AddWithValue("#NAUN", TXT_NAUN.Text);
command.Parameters.AddWithValue("#HPW", hash);
foreach (char chara in result)
{
int temp = 0;
temp = System.Convert.ToInt32(chara);
result = result + temp;
}
result = result + 1;
command.Parameters.AddWithValue("#NAPI", result);
command.Parameters.AddWithValue("#NAPI", result);
dbConn.Open();
int rowsAffected = cmd.ExecuteNonQuery(); ///error appears here
dbConn.Close();
}
}
}
}
Any suggestions on solution, have tried a lot and this is my last hope!
Thanks,
Blackclaw_
At the line you got the error, you are using cmd (the select command). I think you want to use command (the insert command).

Code execution is not going down

I have a code below and it has strange behavior,Line of code after closing of While Loop is not executing. If i write those lines before While loop they got executed. I have searched a lot on this issue but failed.
if ((Convert.ToInt32(newDt.Rows[i]["qty"])) > (Convert.ToInt32(newDt1.Rows[i]["qty"])))
{
k_batch = Convert.ToInt32(newDt.Rows[i]["batch_num"]);
label20.Content = k_batch.ToString();
var dqty = (from row in Addition_result.AsEnumerable() //retriving value from DataTable
where row.Field<int>("batch_num") == k_batch
select row.Field<int>("qty")).FirstOrDefault();
dqty_y = Convert.ToInt32(dqty);
label16.Content = dqty_y.ToString();
con.Open();
SqlCommand cmd1 = new SqlCommand("SELECT quantity,sold_qty,left_qty FROM batch WHERE id='" + k_batch + "'", con);
SqlDataReader batch_qty_details = null;
batch_qty_details = cmd1.ExecuteReader();
while (batch_qty_details.Read())
{
label16.Content = dqty_y.ToString();
batch_qty = Convert.ToInt32(batch_qty_details["quantity"]);
batch_left = Convert.ToInt32(batch_qty_details["left_qty"]);
batch_sold = Convert.ToInt32(batch_qty_details["sold_qty"]);
} //code after this is not executing
label18.Content = batch_left.ToString();
label19.Content = batch_sold.ToString();
label21.Content = dqty_y.ToString();
label22.Content = batch_qty.ToString();
label16.Content = batch_sold + dqty_y;
label17.Content = batch_left - dqty_y;
if (((batch_sold + dqty_y) <= batch_qty) && ((batch_left - dqty_y) >= 0))
{
SqlCommand command = new SqlCommand("update batch set sold_qty=sold_qty+#soldqty2, left_qty=left_qty-#soldqty2 where id=#id2", con);
command.Parameters.AddWithValue("#soldqty2", Convert.ToInt32(dqty_y));
command.Parameters.AddWithValue("#id2", Convert.ToInt32(k_batch));
rexe = command.ExecuteNonQuery();
}
else
{
MessageBox.Show("Please Check you Ordered Quantity !");
}
con.Close();
}
}
Actually there was issue that connection state was already Open and i was trying to open it again. So then i used try-catch block it told me that connection is already open. Now i have changed my code and here it is.
if ((Convert.ToInt32(newDt.Rows[i]["qty"])) > (Convert.ToInt32(newDt1.Rows[i]["qty"])))
{
k_batch = Convert.ToInt32(newDt.Rows[i]["batch_num"]);
label20.Content = k_batch.ToString();
var dqty = (from row in Addition_result.AsEnumerable() //retriving value from DataTable
where row.Field<int>("batch_num") == k_batch
select row.Field<int>("qty")).FirstOrDefault();
dqty_y = Convert.ToInt32(dqty);
label16.Content = dqty_y.ToString();
try
{
//con.Open();
SqlCommand cmd1 = new SqlCommand("SELECT quantity,sold_qty,left_qty FROM batch WHERE id='" + k_batch + "'", con);
SqlDataReader batch_qty_details = null;
batch_qty_details = cmd1.ExecuteReader();
while (batch_qty_details.Read())
{
label16.Content = dqty_y.ToString();
batch_qty = Convert.ToInt32(batch_qty_details["quantity"]);
batch_left = Convert.ToInt32(batch_qty_details["left_qty"]);
batch_sold = Convert.ToInt32(batch_qty_details["sold_qty"]);
}
con.Close();
}
catch(Exception EX)
{
MessageBox.Show(EX.ToString());
}
label18.Content = batch_left.ToString();
label19.Content = batch_sold.ToString();
label21.Content = dqty_y.ToString();
label22.Content = batch_qty.ToString();
label16.Content = batch_sold + dqty_y;
label17.Content = batch_left - dqty_y;
if (((batch_sold + dqty_y) <= batch_qty) && ((batch_left - dqty_y) >= 0))
{
con.Open();
SqlCommand command = new SqlCommand("update batch set sold_qty=sold_qty+#soldqty2, left_qty=left_qty-#soldqty2 where id=#id2", con);
command.Parameters.AddWithValue("#soldqty2", Convert.ToInt32(dqty_y));
command.Parameters.AddWithValue("#id2", Convert.ToInt32(k_batch));
rexe = command.ExecuteNonQuery();
}
else
{
check_qty = -1;
}
}

c# Mysql There is already an open DataReader associated with this Connection

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 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();

Categories

Resources