I'm trying to insert this string 2021-02-22T16:11 into sqlite database. I use VARCHAR(20) to store this this string. When I execute sql query from SQLite studio everything is fine.
But when I run the same code from my ASP Net Core app, it throws an error:
code = Error (1), message = System.Data.SQLite.SQLiteException (0x800007BF):
SQL logic error unrecognized token: "22T16"
I've tried different data types for this column (TEXT, STRING, DATETIME), but nothing works. Can't understand why it can't insert string even into VARCHAR column.
The function that invokes insert query:
public async Task<int> AssignTaskToUser(SaveTaskRequest req, int userId)
{
using (SQLiteConnection connection = new SQLiteConnection(_configuration.GetConnectionString("Default")))
{
long nextInvokeUnix = ((DateTimeOffset)DateTime.Parse(req.NextInvoke)).ToUnixTimeSeconds();
long intervalUnix = ((DateTimeOffset)DateTime.Parse(req.TimeInterval)).ToUnixTimeSeconds() +
(3600 * 24) * req.DaysInterval;
connection.Open();
SQLiteCommand command = new SQLiteCommand();
command.CommandText = $"INSERT INTO UserTasks " +
$"(Name, UserId, TaskId, NextInvokeString, NextInvokeUnix, DaysInterval, TimeInterval, IntervalUnix)" +
$"VALUES ({req.Name}, {userId}, {req.TaskId}, {req.NextInvoke}, {nextInvokeUnix}, {req.DaysInterval}, {req.TimeInterval}, {intervalUnix});" +
$"{getLastIdRequest}";
command.Connection = connection;
long userTaskId = (long)(await command.ExecuteScalarAsync());
foreach (var param in req.parameters)
{
command.CommandText = $"INSERT INTO UserTaskParameters " +
$"(UserTaskId, PrameterId, Value)" +
$"VALUES ({userTaskId}, {param.ParameterId}, {param.Value});";
await command.ExecuteScalarAsync();
}
return await GetChangesAsync(connection);
}
}
Table create script
CREATE TABLE UserTasks(
Id INTEGER PRIMARY KEY AUTOINCREMENT,
Name VARCHAR(30) NOT NULL,
UserId INTEGER NOT NULL,
TaskId INTEGER NOT NULL,
NextInvokeString VARCHAR(20),
NextInvokeUnix INTEGER,
DaysInterval INTEGER,
TimeInterval VARCHAR(6),
IntervalUnix INTEGER,
FOREIGN KEY (UserId)
REFERENCES Users (Id),
FOREIGN KEY (TaskID)
REFERENCES APITasks (Id)
);
Did you try to use this instead
2021-02-22T16:11:59
//or
2021-02-22T16:11:00
and maybe you can try this too:
$"VALUES ( '{req.Name}', {userId}, {req.TaskId}, '{req.NextInvoke}', {nextInvokeUnix}, ...
Related
I have a SQLite Connection Object and a command object. I insert a row in my table using the ExecuteNonQuery function. How do I get the value of the autoincrement column (ID) from this?
Code for creating database:
creationQuery = "CREATE TABLE IF NOT EXISTS MyTable ( ID INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT ,MyCol1 NVARCHAR, MyCol2 NVARCHAR)";
My code for inserting values in the DB:
public void InsertIntoDB(string[] vals){
// Global connection objects (This is in an API so every time a new instance of these are created)
connObj = CreateConnection();
cmdObj = connObj.CreateCommand();
cmdObj.CommandText = "INSERT INTO MyTable ('MyCol1',MyCol2) VALUES( '" + vals[0] + "','" + vals[1] + "')";
int id = -1;
try{
cmdObj.ExecuteNonQuery();
id = (int)cmdObj.Parameters["id"].Value; // tried "#id" as well
}catch(Exception ex){
throw ex;
}
}
This code is inserting correctly. But throws an exception ( System.ArgumentOutOfRangeException) in the line where I'm trying to get the ID. Whats going on/ How do i solve this?
EDIT 1: Inside the try block, I added code to just run another query "Select max(ID) from MyTable":
try
{
cmdObj.ExecuteNonQuery();
cmdObj.CommandText = "Select Max(id) from MyTable";
SQLiteDataReader myReader = cmdObj.ExecuteReader();
while (myReader.Read())
{
id = (int)myReader["id"];
}
Console.WriteLine(id);
}
This code throws the same Exception.
select last_insert_rowid();
And you will need to execute it as a scalar query.
string sql = #"select last_insert_rowid()";
long lastId = (long)command.ExecuteScalar(sql); // Need to type-cast since `ExecuteScalar` returns an object.
I want to run sql statement which I frist read from .sql file.
I'm getting this error:
{"There was an error parsing the query. [ Token line number = 13,Token line offset = 1,Token in error = ALTER ]"}
There is my sql statement in .sql file:
CREATE TABLE [Test]
(
[Id] INT NOT NULL IDENTITY (1,1),
[DatabaseVersion] NVARCHAR(20) NOT NULL,
[Autorun] BIT,
[CurrentCulture] NVARCHAR(10),
[MailNotificationEnabled] BIT,
[RefreshInterval] INT,
[ModifiedDate] DATETIME NOT NULL,
[schemat] NVARCHAR(255)
)
ALTER TABLE [Test] ADD CONSTRAINT [PK_Test] PRIMARY KEY ([Id])
UPDATE [AppConfig]
SET [DatabaseVersion] = '0.12'
Reading file:
string oldVersion = GetOldDatabaseVersion();
string sqlScript = "";
sqlScript = GetScriptFromAssembly(oldVersion,
ConfigurationSettings.ValidDatabaseVersion);
ExecuteNonQuery(CommandType.Text, sqlScript);
ExecuteNonQuery method:
public int ExecuteNonQuery(CommandType type, string sql)
{
using (SqlCeConnection connection = CreateConnection())
{
return ExecuteNonQuery(connection, type, sql);
}
}
private int ExecuteNonQuery(SqlCeConnection connection, CommandType type, string sql)
{
using (SqlCeCommand command = new SqlCeCommand())
{
command.Connection = connection;
command.CommandType = type;
command.CommandText = sql;
return command.ExecuteNonQuery();
}
}
I doesn't know how to resolve it. When I run script dirctly on db it works.
Solved:
string sqlScript = GetScriptFromAssembly(GetOldDatabaseVersion(), ConfigurationSettings.ValidDatabaseVersion);
string[] scripts = sqlScript.Split(new string[] { #"/*$$*/" }, StringSplitOptions.None);
foreach(var script in scripts)
ExecuteNonQuery(CommandType.Text, script);
Added delimiters to sql:
CREATE TABLE [Test]
(
[Id] INT NOT NULL IDENTITY (1,1),
[DatabaseVersion] NVARCHAR(20) NOT NULL,
[Autorun] BIT,
[CurrentCulture] NVARCHAR(10),
[MailNotificationEnabled] BIT,
[RefreshInterval] INT,
[ModifiedDate] DATETIME NOT NULL,
[schemat] NVARCHAR(255)
)
/*$$*/
ALTER TABLE [Test] ADD CONSTRAINT [PK_Test] PRIMARY KEY ([Id])
/*$$*/
UPDATE [AppConfig]
SET [DatabaseVersion] = '0.12'
You must run each statement as a seperate command, you can use code like the helper function to seperate into commands if you seperate each command with GO:
https://github.com/ErikEJ/SqlCeToolbox/blob/master/src/API/Repositories/ServerDBRepository.cs#L639
As you can see I am using SqlCommandReaderStreamed from the DbUp package to do this
Please use the Go keyword before the Alter the table
Recently, I have been working on a C# plugin for a game I play. My problem at the moment is that the query listed below is generating many errors, such as these errors:
MySql.Data.MySqlClient.MySqlException: Data too long for column 'lastServer' at row 1
^^This error shows when my lastServer data type is varchar(10), but when I changed it to varchar(25), it went away. However I would still like to know why this would be, if anyone is able to figure it out.
.
My current error is having #lastServer, #characterName, and #ip showing up as #lastServer, #characterName, and #ip instead of their "AddWithValue" values.
Here's the query used for Table Creation:
command.CommandText = string.Concat("CREATE TABLE `", MDiscipline.Instance.Configuration.Instance.PlayerInfoTableName, "` (`steamId` varchar(32) NOT NULL,`characterName` varchar(40) NOT NULL,`ip` varchar(15) NOT NULL, `lastPunishment` tinyint(2) UNSIGNED NOT NULL,`lastServer` varchar(25) NOT NULL,`lastLogin` TIMESTAMP NOT NULL DEFAULT current_timestamp, PRIMARY KEY (`steamId`)) ");
And Here is the Code I'm having problems with:
public void UpdatePlayerInfo(string steamid, string characterName, string ip)
{
try
{
MySqlConnection connection = createConnection();
MySqlCommand command = connection.CreateCommand();
command.Parameters.AddWithValue("#steamId", steamid);
command.Parameters.AddWithValue("#characterName", characterName);
command.Parameters.AddWithValue("#ip", ip);
command.Parameters.AddWithValue("#lastServer", MDiscipline.Instance.Configuration.Instance.Instance);
command.CommandText = "UPDATE `" + MDiscipline.Instance.Configuration.Instance.PlayerInfoTableName + "` SET `characterName` = '#characterName', `ip` = '#ip', `lastServer` = '#lastServer', `lastLogin` = NOW() WHERE `steamId` = '" + steamid.ToString() + "';";
connection.Open();
command.ExecuteNonQuery();
connection.Close();
}
catch (Exception ex)
{
Logger.LogException(ex);
}
}
Helpful info to understand variables:
MDiscipline.Instance.Configuration.Instance.PlayerInfoTableName can be translated to "player_info".
steamid or (#steamId) can be translated to a 32 char number.
characterName or (#characterName) can be translated to any value between 1 and 30 characters.
ip or (#ip) can be translated to an ip address in a string, such as "255.255.255.255".
MDiscipline.Instance.Configuration.Instance.Instance or (#lastServer) can be translated to Server01.
I have two tables (Primary_Table and Secondary_table). Primary_Table contains primary key which is a foreign key for Secondary_table. Whenever I insert a new row into Primary_table I need to take its primary key and insert it into secondary_table. I am facing difficulties in taking primary key as a parameter. I need help on this.
string connString = "Database=MyServerDB;Server=ATLW732FV000169\SQLEXPRESS;Integrated Security=True;connect timeout = 30";
SqlConnection myConnection = new SqlConnection(connString);
try
{
myConnection.Open();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
using (SqlCommand command = new SqlCommand("INSERT INTO Primary_Table (TransactionType, Country) "VALUES (#transactionType, #country);" +
"INSERT INTO Secondary_table (BookingID,TripID) VALUES (#bookingID, #tripID);" , myConnection))
{
// declaring Primary_Table paramteres
command.Parameters.AddWithValue("#transactionType", "S");
command.Parameters.AddWithValue("#country", "US");
// declaring Secondary_table parameters
command.Parameters.Add("#bookingID", *****); // Not sure how to insert bookingID (priamry key) into Secondary Table
command.Parameters.AddWithValue("#tripID", "tr");
try
{
Int32 lines = command.ExecuteNonQuery();
Console.WriteLine("Lines affected " + lines);
}
catch (SqlException ex)
{
Console.WriteLine(ex.Message);
}
}
Define a trigger AFTER INSERT on Primary_Table that will take primary key of inserted data and insert it in to secondary_table.
Do this:
After your first insert -
DECLARE #var int
#var = select top 1 [pk] from table1 order by pk desc
This will get you the most recent record from table1 with #var being the pk, then simply...
insert into table2 ([fk]) values (#var)
This is easiest to do inside a stored procedure, which is considered best practice anyways (don't do inline SQL in your .NET code ever).
you can insert in to primary and secondary table via one storedprocedure in sql :
declare #Primary_Id int
INSERT INTO Primary_Table (TransactionType, Country) VALUES (#transactionType, #country)
set #Primary_Id =##identity
INSERT INTO Secondary_table (BookingID,TripID) VALUES (#bookingID, #Primary_Id)
and then in code :
command.CommandType= CommandType.StoredProcedure;
I have a series of data that need to be written into SQL, what should I do to check the data in SQL to prevent same data inserted into table?
Example data to be inserted:
David
James
John
If the 4th data is John again, I want the system to skip the duplicate record (John).
So far I have:
SqlConnection myCnn = new SqlConnection(cnn);
String _state = "Insert into CamNo1(platename, date, camID, path, filename) OUTPUT INSERTED.platename values(#msg, getdate(), #camID, #path, #filename)";
SqlCommand _Query = new SqlCommand(_state, myCnn);
_Query.Parameters.AddWithValue("#msg", msg);
_Query.Parameters.AddWithValue("#camID", camID);
_Query.Parameters.AddWithValue("#path", imageFile);
_Query.Parameters.AddWithValue("#filename", name);
try
{
myCnn.Open();
string checkname = (string)_Query.ExecuteScalar();
myCnn.Close();
getcheckname = checkname;
Console.WriteLine("OK");
}
catch (Exception)
{
}
i got the string value checkname that is last inserted, what should i do check the data?
First, you can prevent a duplicate from ever occurring in the table by using a unique index or constraint. An index/constraint can work in concert with the suggestions below. If you only use a unique index and not one of the below solutions, inserting a duplicate record will throw an error and you will need to handle that on the other end.
Additionally, I would probably insert the data via a stored procedure that checks to see if the row already exists. To do that, you can use either a MERGE statement, as shown in this pseudo code:
create procedure MyProcedure
(
#Name nvarchar(100),
...
)
as
merge MyTable
using
(
select #Name,...
) as source (Name, ...)
on MyTable.Name = source.Name
when not matched then
insert (Name,...) values (source.Name,...)
when matched then
update set Name = #Name,...
or, you could check for the records existence and insert or update manually:
create procedure MyProcedure
(
#Name nvarchar(100),
...
)
as
if not exists (select * from MyTable where Name = #Name)
begin
insert into MyTable (Name,...) values (#Name,...)
end
else
begin
update MyTable
set ...
where Name = #Name
end
If you do not want duplicate data, you should consider enforcing that at the DB level with a UNIQUE CONSTRAINT or a UNIQUE INDEX
SQL Server 2008 also has a MERGE statement you could use to check for matched records. This could be helpful if you want to update an existing record.
If you want to prevent duplicate data from being inserted, you could use a unique index or unique constraint on those fields.
If you want to just run a hard insert statement, but have it do nothing if a value exists, something like this should work. I tested this on a local database I have:
declare #subject as varchar(100);
set #subject = 'hello'
insert into Subjects ([name])
select #subject
where not exists (select 1 from Subjects where [name] = #Subject)
Try This Easy way
{
DataSet ds = New DataSet();
SqlConnection myCnn = New SqlConnection(cnn);
myCnn.Open();
SqlCommand _Query = New SqlCommand("Select *FROM CamNo1 where platename='" + Console.ReadLine + "' ", myCnn);
SqlDataAdapter sda = New SqlDataAdapter(_Query);
sda.Fill(ds);
Int i = ds.Tables[0].Rows.Count;
If (i > 0) Then
{
MessageBox.Show("platename" + Console.WriteLine + "Already Exists ");
ds.Clear();
}
Else
{
SqlConnection myCnn = New SqlConnection(cnn);
String _state = "Insert into CamNo1(platename, date, camID, path, filename) OUTPUT INSERTED.platename values(#msg, getdate(), #camID, #path, #filename)";
SqlCommand _Query = New SqlCommand(_state, myCnn);
_Query.Parameters.AddWithValue("#msg", msg);
_Query.Parameters.AddWithValue("#camID", camID);
_Query.Parameters.AddWithValue("#path", i`enter code here`mageFile`);
_Query.Parameters.AddWithValue("#filename", Name);
Try
{
myCnn.Open();
String checkname = (String)_Query.ExecuteScalar();
myCnn.Close();
getcheckname = checkname;
Console.WriteLine("OK");
}
Catch (Exception)
{
}
}
}