I found several examples of how to get the last inserted row id from an sql insert call to my SQLite database, but my script threw this error:
SQLiteException
Message = "SQLite error\r\nnear \")\": syntax error"
InnerException
NULL
Below is the SQL text I sent in and how I used it. Obviously, I misunderstood something. Could someone help me out here?
I am trying to return the ID number that was just inserted.
private static int Save(Dates date, SQLiteConnection con) {
// REF: http://www.sqlite.org/c3ref/last_insert_rowid.html
int result = 0;
string sql = "INSERT INTO Dates1 " +
"(ID, TaskID, Last1) " +
"VALUES " +
"((SELECT MAX(ID) FROM Dates1)+1, #TaskID, #Last); " +
"SELECT sqlite3_last_insert_rowid(sqlite3*);";
using (SQLiteCommand cmd = new SQLiteCommand(sql, con)) {
cmd.Parameters.AddWithValue(Dates.AT_TASK, date.TaskID);
cmd.Parameters.AddWithValue(Dates.AT_LAST, date.Last.ToShortDateString());
cmd.CommandText = Dates.SQL_INSERT;
try {
result = cmd.ExecuteNonQuery();
} catch (SQLiteException err) {
result = -1;
LogError("Save(Dates, SQLiteConnection)", err);
}
}
return result;
}
FYI: I have set up the table so that ID is supposed to be auto generated using the Create SQL below, but the table only stores -1 for the ID values unless I manually insert it.
public const string SQL_CREATE = "CREATE TABLE Dates1 " +
"(ID INTEGER PRIMARY KEY AUTOINCREMENT, TaskID INTEGER, Last1 TEXT);";
To quote from the SQLite documentation:
last_insert_rowid() The last_insert_rowid() function returns the ROWID of the last row insert from the database connection which invoked the function. The last_insert_rowid() SQL function is a wrapper around the sqlite3_last_insert_rowid() C/C++ interface function.
So you need to change your statement to:
"SELECT last_insert_rowid();"
because what you did was to try and call the C API function.
Related
I'm very much a novice with C# to SQL interaction so apologies if the problem here is obvious or a duplicate. I'm trying to insert a new row into the table 'Clientes', the first part of this code connects to the database, then checks the table for duplicates, I know those parts work. I included it just in case maybe the problem maybe comes from my connection string or something.
Once it gets to the Try Catch, it throws up the "Error" message I put in there, so I know the failure is happening while inserting.
Usually I can work things like this out based on info from the error message but this is only giving me
[Exception thrown: 'System.Data.SqlClient.SqlException' in System.Data.dll]
in the output tab, nothing in the error list and no further details that I can find, and I've been unable to deduce the problem based on similar SO posts.
if ( textBox_tel.Text.All(c => char.IsDigit(c))) //checks no letters in phone number
{
string connectionstring;
SqlConnection con;
connectionstring = #"Data Source = DRAGONSLAYER;Initial Catalog=bancodb;User id=bancodb_admin;Password=admin";
con = new SqlConnection(connectionstring);
con.Open(); //now connected to the DB
string querysignupsubmitcheck = "Select * from Clientes Where Login = '" + textBox_usr.Text + "'";
SqlDataAdapter sda_signupsubmitcheck = new SqlDataAdapter(querysignupsubmitcheck, con);
DataTable dtbl_signupsubmitcheck = new DataTable();
sda_signupsubmitcheck.Fill(dtbl_signupsubmitcheck);
con.Close();
if (dtbl_signupsubmitcheck.Rows.Count < 1) //checks the new client row isn't a duplicate
{
try
{
string querysignupsubmit = "Insert into Clientes (Nombre, Telefono, Login, Password) Values (" +
textBox_name.Text + ", " +
textBox_tel.Text + ", " +
textBox_usr.Text + ", " +
textBox_pword2.Text + ")";
SqlCommand sc_signupsubmitc = new SqlCommand(querysignupsubmit, con);
sc_signupsubmitc.ExecuteNonQuery();
this.Close();
objform_login.Show();
}
catch { label_alert.Text = "ERROR DE BASE DE DATOS"; }
}
else
{
label_alert.Text = "usuario ya existe";
}
}
else
{
label_alert.Text = "Telefono acepta solo numeros";
}
based on something suggested on another question here, I changed the code inside the try-catch statement to this, but it still throws the same exception:
using (con)
{
string querysignupsubmit = "INSERT INTO Clientes (Nombre, Telefono, Login, Password) VALUES (#val1, #val2, #val3, #val4)";
using (SqlCommand sc_signupsubmit = new SqlCommand())
{
sc_signupsubmit.Connection = con;
sc_signupsubmit.CommandText = querysignupsubmit;
sc_signupsubmit.Parameters.AddWithValue("#val1", textBox_name.Text);
sc_signupsubmit.Parameters.AddWithValue("#val1", textBox_tel.Text);
sc_signupsubmit.Parameters.AddWithValue("#val1", textBox_usr.Text);
sc_signupsubmit.Parameters.AddWithValue("#val1", textBox_pword2.Text);
con.Open();
sc_signupsubmit.ExecuteNonQuery();
con.Close();
this.Close();
objform_login.Show();
}
}
Any help or suggestions are appreciated, this is the code for the table I'm trying to insert into:
CREATE TABLE [dbo].[Clientes] (
[ClienteID] INT IDENTITY (1, 1) NOT NULL,
[Nombre] VARCHAR (255) NOT NULL,
[Telefono] VARCHAR (20) NOT NULL,
[Login] VARCHAR (255) DEFAULT ('default_login') NOT NULL,
[Password] VARCHAR (128) NOT NULL,
CONSTRAINT [PK_Clientes] PRIMARY KEY CLUSTERED ([ClienteID] ASC)
);
EDIT:
Here is the full output and error list tabs, the exit message is from me closing it
EDIT2: I am dumb and declared Val1 multiple times, dumb dumb. Thanks for all the help y'all.
I added a breakpoint (right click inside a pair of brackets if you're using VSC) to my Catch statement as #Jamiec suggested. Then, while poking around with the debugging tabs, I found on the Watch tab to the left of the output I can keep track of a value in realtime. So I added the ex exception to the Watch and this message came up:
{"The variable name '#val1' has already been declared. Variable names must be unique within a query batch or stored procedure.\r\nMust declare the scalar variable "#val2"."}
I had accidentally declared val1 like four times in a row in my SqlCommand and somehow failed to notice it on multiple read-throughs.
I am making DatabaseManager class for my solution and I am getting the number 0 when I am trying to update the text.
For example : I have now the name michael and I wanted to change it to "michael , mike" so I'll probably use update.
public void AddCrime(CSteamID id, string crime, string time)
{
try
{
MySqlConnection connection = createConnection();
MySqlCommand command = connection.CreateCommand();
crime = "," + crime;
command.CommandText = "update `" + Main.Instance.Configuration.Instance.DatabaseTableName
+ "` set `crime` = crime + ( #crime ) where `steamId` = #steamID; select `crime` from `"
+ Main.Instance.Configuration.Instance.DatabaseTableName
+ "` where `steamId` = #steamID";
command.Parameters.AddWithValue("#steamID", id);
command.Parameters.AddWithValue("#crime", crime);
connection.Open();
command.ExecuteNonQuery();
connection.Close();
AddTime(id, time);
}
catch (Exception ex) { Logger.Log(ex); }
}
How do I call it :
DatabaseManager.AddWanted(player.CSteamID, command[1], command[2]);
Thanks everyone!
yor last sentence in your command is a select statement, NonQuery does not return values, only the number of rows affected. Change it to ExecuteScalar and store the value of the select in a variable.
Second error is the data type of the parameter #steamID. You set the value id, which is declares as CSteamID id... CStreamId is not string, change the AddWithValue
Fixed, I added another method to get crime from table and then changed the void crime string to the current string + the table text.
The error was : Truncated incorrect DOUBLE value.
I need to insert a new row in a mysql table using C#.
The table looks like this, and contains one foreign key column.
i use the follwing code to cinnect to the database and insert data.
public virtual void addToDB()
{
try
{
//prepare for query
var cmd = MySQL.readyQuery();
//insert testdata to Vo2test
cmd.CommandText = "INSERT INTO vo2test_tb(ClientID, Weight, Methods, TimeOfDay, Date, StartResistance, Endresistance, TheoreticalMaxPulse, FatPercent3point, FatPercent7point, VO2_max, FitnessRating, HRmax, RERmax, TestTime, Raw_test_data) VALUES((SELECT UserID from user_tb WHERE UserID = '#UserID'), '#Weight', '#Method', '#Timeofday', '#Date', '#Startresistance', '#Endresistance', '#Theoreticalmaxpulse', '#Fatprocent3p', '#Fatprocent7p', '#vo2max', '#fitnessrating', '#hrmax', '#rermax', '#testtime', '#rawtestdata')";
cmd.Prepare();
//insert parameters som skal ændres:
cmd.Parameters.AddWithValue("#UserID", UserID);
cmd.Parameters.AddWithValue("#Weight", Weight);
cmd.Parameters.AddWithValue("#Method", Method);
//coverts date to 0000-00-00
string DateString = Convert.ToString(TestDate.Date.Date.Year) + "-" + Convert.ToString(TestDate.Date.Month) + "-" + Convert.ToString(TestDate.Date.Day);
cmd.Parameters.AddWithValue("#Date", DateString);
//converts time to 00:00:00.
string TimeString = Convert.ToString(TimeOfDay.Hour) + ":" + Convert.ToString(TimeOfDay.Minute) + ":00";
cmd.Parameters.AddWithValue("#Timeofday", TimeString);
cmd.Parameters.AddWithValue("#Startresisstance", StartResistance);
cmd.Parameters.AddWithValue("#Endressistance", EndResistance);
cmd.Parameters.AddWithValue("#TheoreticalMaxPulse", TheoreticMaxPulse);
cmd.Parameters.AddWithValue("#FatPercent3point", FatPercent3Point);
cmd.Parameters.AddWithValue("#FatPercent7point", FatPercent7Point);
cmd.Parameters.AddWithValue("#VO2_max", Vo2Max);
cmd.Parameters.AddWithValue("#FitnessRating", FitnessRating);
cmd.Parameters.AddWithValue("#HRmax", HRmax);
cmd.Parameters.AddWithValue("#RERmax", RERmax);
cmd.Parameters.AddWithValue("#TestTime", TimeOfDay);
cmd.Parameters.AddWithValue("#Raw_test_data", RawTestData);
cmd.ExecuteNonQuery();
//close connection
cmd.Connection.Close();
}
catch (MySqlException ex)
{
Console.WriteLine(ex.Message);
}
}
when i run it, i am told that ClientID can't be null but if i just run the sql query in Adminer it works fine.
The sub select in your insert query doesnt make sense. Why are you doing a sub select to insert a value you already have.
SELECT UserID from user_tb WHERE UserID = '#UserID'
Just insert #UserID directly.
Also you have wrapped all your # parameters in single quotes in the query string. You do not need this. Parameterization deals with the quotes for you in the background. Remove all single quotes so that it just reads:
cmd.CommandText = "INSERT INTO vo2test_tb(ClientID, Weight, Methods, TimeOfDay, Date,
StartResistance, Endresistance, TheoreticalMaxPulse, FatPercent3point, FatPercent7point,
VO2_max, FitnessRating, HRmax, RERmax, TestTime, Raw_test_data)
VALUES((SELECT ClientID from user_tb WHERE UserID = #UserID), #Weight, #Method, #Timeofday,
#Date, #Startresistance, #Endresistance, #Theoreticalmaxpulse, #Fatprocent3p, #Fatprocent7p,
#vo2max, #fitnessrating, #hrmax, #rermax, #testtime, #rawtestdata)";
I'm attempting to programmatically create a SQL table. I can create a table with a query, this is no issue at all. But I'd like the table name to have some relevance to the data inserted into it, as it's being used for quotations and invoices. Data entered from a DataGridView will be inserted into it (probably via bulkcopy, or something similar).
using (SqlCeCommand command = new SqlCeCommand(
"CREATE TABLE table1' (Weight INT, Name NVARCHAR, Breed NVARCHAR)", con))
works perfectly. However I'd like this code to work:
using (SqlCeConnection con = new SqlCeConnection(#"Data Source=|DataDirectory|\LWADataBase.sdf"))
{
con.Open();
try
{
string tableName = "" + quotenameTxt.Text + "-" +firstTxt.Text+ "-" + surenameTxt.Text;
using (SqlCeCommand command = new SqlCeCommand(
"CREATE TABLE '"+tableName.ToString()+"' (Weight INT, Name NVARCHAR, Breed NVARCHAR)", con))
{
command.ExecuteNonQuery();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Any suggestions? I get an error (as expected) but are unsure what I need to do.
I'm using SqlCe (and before anyone says "BulkCopy isn't supported", I know, I've got a reference that allows it)
The error I get is :
There was an error parsing the query. [ Token line number = 1,Token line offset = 16,Token in error = 1-2-3 ]
// "1-2-3" being the textbox values.
Change the dashes to underscores or surround the entire table name with [square brackets]
As was mentioned in comments above, make the following changes:
using (SqlCeCommand command = new SqlCeCommand(
"CREATE TABLE '"+tableName+"' (Weight INT, Name NVARCHAR, Breed NVARCHAR)", con))
tableName is already a string. No need to use .ToString() on it.
Also, you have a leading white space in your declaration of tableName:
string tableName = "" + quotenameTxt.Text + "-" + firstTxt.Text + "-"
+ surenameTxt.Text;
This makes the string " 1-2-3", not the "1-2-3" you are expecting.
Lastly, surround your tableName with [] to get it to work correctly:
using (SqlCeCommand command = new SqlCeCommand(
"CREATE TABLE '[" + tableName + "]' (Weight INT, Name NVARCHAR, Breed NVARCHAR)", con))
I have a web application that writes to several databases for tracking employee change requests. I am running into a problem with entering in a new employee. They are first written to main Employee database before their access information is written to the other databases with EMP_ID being the primary key. When it goes to write to the other databases EMP_ID has been generated yet so it is getting entered in as 0.
To resolve this I was trying to loop and check the EMP_ID value until a value is generated but I continue to get stuck in a loop because the query returns back that no value was found.
while (int.Parse(empIDChecker) == 0)
{
dbConnection.Open();
validateIDSQLString = "SELECT EMP_ID FROM EMPLOYEE_TABLE WHERE FIRST_NAME = '" + firstNameTextBox.Text.Trim() + "' AND LAST_NAME = '" + lastNameTextBox.Text.Trim() + "'";
SqlCommand updateSQLCmd = new SqlCommand(validateIDSQLString, dbConnection);
SqlDataReader getRecords = updateSQLCmd.ExecuteReader();
try
{
empIDChecker = getRecords["EMP_ID"].ToString();
}
catch
{
empIDChecker = "0";
}
getRecords.Close();
dbConnection.Close();
}
OK, so if your insert sproc looks something like:
sp_InsertEmp
...
INSERT INTO Emp(Name, etc...)
VALUES ('Paul', etc...)
SELECT SCOPE_IDENTITY() AS EMP_ID
GO
And in your code:
SqlCommand insertCmd = new SqlCommand("sp_InsertEmp", dbConnection);
... Add parameters here and set type to StoredProcedure
SqlDataReader dr= insertCmd.ExecuteReader();
int newId;
if (dr.Read())
{
newId = dr.GetInteger(0);
}
you can use
SELECT IDENT_CURRENT(‘tablename’)
This will give you the last inserted auto increment ID of the table, you can use that to insert in other table
Check this link as well http://blog.sqlauthority.com/2007/03/25/sql-server-identity-vs-scope_identity-vs-ident_current-retrieve-last-inserted-identity-of-record/