AUTOINCREMENT does not work on OleDbCommand - c#

I'm doing MS Access database file using OleDb. Here is the snippet:
OleDbCommand command = oleDbConnection.CreateCommand();
command.CommandText =
"CREATE TABLE MyTable (" +
"[Count] LONG NOT NULL PRIMARY KEY AUTOINCREMENT, " +
"[TimeAndDateTested] TIMESTAMP NOT NULL, " +
"[SerialNumber] VARCHAR(14) NOT NULL, " +
"[TestResult] BIT NOT NULL)";
command.ExecuteNonQuery();
Do you know what's wrong? Thanks.

In Access 2003, this statement will create the table structure I think you want. Notice I changed the name of the first field to Kount because Count is a reserved word in Access. You could enclose the name in square brackets to avoid ambiguity, but I prefer to just avoid using reserved words as object names. TIMESTAMP is recognized as a synonym for DATETIME. VARCHAR is recognized as a synonym for TEXT. BIT will get you a field type which Access calls Yes/No.
CREATE TABLE MyTable2 (
Kount COUNTER CONSTRAINT pkey PRIMARY KEY,
TimeAndDateTested TIMESTAMP NOT NULL,
SerialNumber VARCHAR(14) NOT NULL,
TestResult BIT NOT NULL);
I assigned a primary key constraint to Kount, and named the constraint as "pkey". Not Null and unique are implied by the primary key constraint, so you needn't specify them separately.

I change:
"[Count] LONG NOT NULL PRIMARY KEY AUTOINCREMENT, " +
with:
"[Count] IDENTITY NOT NULL PRIMARY KEY, " +
and it worked.

When using DDL against MS Access, you want to use COUNTER to specify an auto-incrementing integer Field.

Related

Setting up tables in Dapper

I'm new to Dapper and currently I'm trying to populate my fresh database.
Since Dapper has no ability to create a table from model directly, how should I populate my database? Are there any good practices other than executing a schema from the variable?
Currently, I'm using this (dirty approach):
public void CreateTables()
{
using (var connection = GetSQLiteHandle())
{
string sql = #"
CREATE TABLE IF NOT EXISTS statistics (
id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
name TEXT NOT NULL,
value TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS posts (
id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
content TEXT NOT NULL,
created TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS names (
id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
name TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
username TEXT NOT NULL,
email TEXT NOT NULL,
created TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS storage (
id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
key TEXT NOT NULL,
value TEXT NOT NULL
);
";
connection.Execute(sql);
}
}
Dapper has no ability to generate tables like Entity Framework. Hence, you may use EF with code first approach. If you want to use Dapper, you can use migrator tools such as fluent migrator and generate db with it.

ASP.NET: Cannot add or update child row: a foreign key constraint fails

i have a strange issue in a asp.net application. I have two tables who save history of some variable changes, one with a foreign key to the other, but for some reason, mysql throws error while inserting to the second table
Cannot add or update a child row: a foreign key constraint fails (`FlowDB/tab_hist_vars_reas`, CONSTRAINT `tab_hist_vars_reas_ibfk_1` FOREIGN KEY (`HIST_REASIG_ID`) REFERENCES `tab_hist_reas` (`HIST_REASIG_ID`))
This is the code that makes the insert into the two tables (assume that local variables have values). I tested locally but when i install the site in the production environment it throws the above error.
string strcmd = "INSERT INTO tab_hist_reas (HIST_REASIG_INC,HIST_REASIG_FLOW,HIST_REASIG_STEP,HIST_REASIG_DATE,HIST_REASIG_USER)";
strcmd += string.Format("VALUES ({0}, '{1}', '{2}', NOW(), '{3}');", incident, flow, step, user);
db.executeNonQuery(strcmd);
strcmd = "SELECT last_insert_id() AS id";
int idHistory = (int)db.ExecuteScalar(strcmd);
foreach(var variable in lstVariables)
{
string strcmd = "INSERT INTO tab_hist_vars_reas (HIST_REASIG_ID,HIST_VAR_REASIG_VAR,HIST_VAR_REASIG_VALUE)";
strcmd += string.Format("VALUES ({0}, '{1}', '{2}');", idHistory, variable.Name, variable.Value);
db.executeNonQuery(strcmd);
}
Here are the table definitions.
CREATE TABLE `tab_hist_reas` (
`HIST_REASIG_ID` int(11) NOT NULL auto_increment,
`HIST_REASIG_INC` int(11) default NULL,
`HIST_REASIG_FLOW` varchar(150) default NULL,
`HIST_REASIG_STEP` varchar(150) default NULL,
`HIST_REASIG_DATE` datetime default NULL,
`HIST_REASIG_USER` varchar(150) default NULL,
PRIMARY KEY (`HIST_REASIG_ID`)
) ENGINE=InnoDB;
CREATE TABLE `tab_hist_vars_reas` (
`HIST_VAR_REASIG_ID` int(11) NOT NULL auto_increment,
`HIST_REASIG_ID` int(11) NOT NULL,
`HIST_VAR_REASIG_VAR` varchar(100) default NULL,
`HIST_VAR_REASIG_VALUE` varchar(100) default NULL,
PRIMARY KEY (`HIST_VAR_REASIG_ID`),
KEY `IND_HIST_VAR_REAS_ID_HIST` (`HIST_REASIG_ID`),
CONSTRAINT `tab_hist_vars_reas_ibfk_1` FOREIGN KEY (`HIST_REASIG_ID`) REFERENCES `tab_hist_reas` (`HIST_REASIG_ID`)
) ENGINE=InnoDB;
I tried replacing the last_insert_id() with ##identity but didn't work either. I tried executing the query directly into the database and it works fine.
A part from the Sql Injection problem that you have in your code, a probable reason for this behavior is the db variable. If this variable is some instance of a custom class that opens and closes the connection every time you call an ExecuteXXX method then you could face a problem with the SELECT LAST_INSERT_ID called in a different connection from the one that inserts the values in the first table.
You could try to merge the two initial commands to have them handled together by the same connection
string strcmd = #"INSERT INTO tab_hist_reas
(HIST_REASIG_INC,HIST_REASIG_FLOW,HIST_REASIG_STEP,
HIST_REASIG_DATE,HIST_REASIG_USER) ";
strcmd += string.Format("VALUES ({0}, '{1}', '{2}', NOW(), '{3}');", incident, flow, step, user);
strcmd += "SELECT last_insert_id() AS id";
int idHistory = (int)db.ExecuteScalar(strcmd);
In this way you exec just one command and you should be sure that the return from the SELECT last_insert_id() is effectively set to the current insert command.

How to insert a new record which has a auto increment number as primary key?

For example, I have the following Table:
CustomerInfo
cus_id: auto increment, int, is Identity
cus_name: nvarchar
If I use the follow codes to insert the record "Peter",
string name = "Peter";
DataContext DC = new DataContext();
CustomerInfo newCustomer = new CustomerInfo();
newCustomer.cus_name = name;
DC.CustomerInfos.InsertOnSubmit(newCustomer);
DC.SubmitChanges();
The following error returns,
Can't perform Create, Update, or Delete operations on 'Table(CustomerInfo)' because it has no primary key.
Do I need to self-define the cus_id or any other solutions? Thanks!
First of all LINQ-To-SQL needs primary keys in order to be able to do Inserts and Updates, so you probably have to add the Primary Key in your table.
Now, because it is an auto incremented identity column, in your dbml, you have to select the column "cus_id" of the "CustomerInfo" table and go to the properties and set the following:
Auto Generated Value : True
Auto-Sync : OnInsert
This will ensure that when you insert a new row it will get a new id.
naratting from answer 1 of question you'll have to make cus_id as primary key too.
you can also try to do following
CREATE TABLE Customers
(
cus_id int NOT NULL AUTO_INCREMENT,
cus_name varchar(255) NOT NULL,
PRIMARY KEY (cus_id)
)
I got this error to. As far as I manged to fix it was to add a primary key.
This code made me a primary key and made it autoincrement. Maybe it's what you are looking for?
(When you create the table)
columnname bigint IDENTITY(1,1) NOT NULL,
CONSTRAINT pkcolumnname PRIMARY KEY CLUSTERED

C#/SQLCE CREATE TABLE programmatically (Auto increment + Primary key)

I am trying to create a table in a SQL CE database programmatically.
Currently, I am using the following query - though I am getting an error;
string command = #"CREATE TABLE CONNECTION(" +
"connection_id INTEGER IDENTITY(1,1) PRIMARY KEY, " +
"host NVARCHAR(255), port INT, key NVARCHAR(50), " +
"last_used NVARCHAR(15));";
The error I am getting is:
There was an error parsing the query. [ Token line number = 1, Token line offset = 104, Token in error = key ]
I can't seem to figure out what I am doing wrong. I am used to MySQL and the queries are slightly different.
try enclosing key in a brackets
string command = #"CREATE TABLE CONNECTION(" +
"connection_id INTEGER IDENTITY(1,1) PRIMARY KEY, " +
"host NVARCHAR(255), port INT, [key] NVARCHAR(50), " +
"last_used NVARCHAR(15));";
Reserved Words

Violation of PRIMARY KEY constraint 'PK_Calle'. Cannot insert duplicate key in object with autoincrement option activated

I'm migrating an old database which has no Identity constraints and I'm adding to the new one and everything worked fine, but when I checked the logs files I've created, I notice this error, the weird part of it is the table have Identity key with autoincrement of 1
The code I'm using is this:
var cmd1 = new SqlCommand();
cmd1.Parameters.Clear();
cmd1.Connection = mySqlConnection;
cmd1.CommandType = CommandType.Text;
cmd1.CommandText = #"INSERT INTO [Tomin].[TominPredial].[Calle]([Nombre],[Id_Colonia]"
+ ",[Id_User],[Id_Date])"
+ " VALUES(#Nombre,#Id_Colonia,#Id_User,#Id_Date)";
cmd1.Parameters.AddWithValue("#Nombre", nombreCalle);
cmd1.Parameters.AddWithValue("#Id_Colonia", id_col);
cmd1.Parameters.AddWithValue("#Id_User", "Admin");
cmd1.Parameters.AddWithValue("#Id_Date", DateTime.Now);
cmd1.ExecuteNonQuery();
I don't know what is this happening since I don't send the primary key because I suppose the autoincrement will set it for me, any idea what's going on?
The value that is the ID that throws the error begins in 1 and ends in 562, when I delete data, after doing it i use DBCC CHECKIDENT('Tomin.TominPredial.Calle', RESEED, 0)
CREATE TABLE TominPredial.Calle (
Id_Calle SMALLINT NOT NULL IDENTITY(1,1) CONSTRAINT PK_Calle PRIMARY KEY,
Nombre NVARCHAR(50) NOT NULL,
Id_Colonia SMALLINT NOT NULL CONSTRAINT FK_Calle_Colonia REFERENCES TominPredial.Colonia (Id_Colonia),
Id_User NVARCHAR(30) NOT NULL CONSTRAINT FK_Calle_User REFERENCES TominUsuario.Usuario (ID),
Id_Date DATETIME2 NOT NULL,
Id_Estatus TINYINT DEFAULT 1 NOT NULL CONSTRAINT FK_Calle_Estatus REFERENCES TominSistema.Estatus (Id_Estatus)
);
GO

Categories

Resources