Inserting record into database column with auto number - c#

I am trying to add a record to my database using the following function
The Error occurs at
adapter.InsertCommand.ExecuteNonQuery();
Full code:
public void Insert()
{
string query;
myDB.Open();
OleDbDataAdapter adapter = new OleDbDataAdapter(#"SELECT * From Eiendom", myDB);
query = #"INSERT INTO Eiendom (AreaID, AgentID, KlientID, AdresID, EiedomAantalBadkamers, EiedomAantalSlaapkamers, EiendomPrys, EiedomSwembad, EiedomGarages, EiedomAantalVloere, EiedomOppervlakte, EiedomTipePlan, EiedomAdisioneleInligting)
VALUES ('" + areaID + " , " + agentID + " , " + klientID + " , "
+ adressID + " , " + badkamers + " , " + slaapkamers + " , " + prys + " . "
+ " , " + swembad + " , " + garages + " , " + vloere + " , " + oppervlakte
+ " , " + plan + " , " + inligting + "')" ;
OleDbCommand insert = new OleDbCommand(query, myDB);
adapter.InsertCommand = insert;
adapter.InsertCommand.ExecuteNonQuery();
DataSet ds = new DataSet();
adapter.Fill(ds, "Eiendom");
dataGridView1.DataSource = ds;
dataGridView1.DataMember = "Eiendom";
myDB.Close();
}
I get an error that says ;
System.Data.OleDb.OleDbException: 'Number of query values and destination fields are not the same.'
I actually do understand as to why this is presenting itself as I am not adding the autonumber column I have in my database
So what I'm asking is what can I do as a workaround to add the record but the auto number column fills itself in when adding the record?

You don't need to hand craft your InsertCommamd. The OleDbCommandBuilder can do it all for you. I think it should deal with Autonumbers.
var cbr = new OleDbCommandBuilder(adapter);
cbr.QuotePrefix = "[";
cbr.QuoteSuffix = "]";
adapter.InsertCommand = cbr.GetInsertCommand(true);

Related

OleDbDataReader does not read last record

I see 5 records to be inserted, but only 4 are inserted. The last record is not inserted, and I can not figure out why. Copying from one database to the other. First is an access database, the second is a sql server database.
OleDbCommand cmd2 = new OleDbCommand();
OleDbDataReader oledbReader2;
using (cmd2 = new OleDbCommand())
{
query = "SELECT ID, STRAATNAAM, 'NL' AS TAALCODE, PKANCODE, CITY FROM Temp_Unique_Streetnames WHERE TRIM(Temp_Unique_Streetnames.STRAATNAAM) <> '' AND ID > " + lastId.ToString() + " ORDER BY ID";
WriteToFile(query);
cmd2.CommandText = query;
cmd2.CommandType = CommandType.Text;
cmd2.Connection = cn2;
using (oledbReader2 = cmd2.ExecuteReader())
{
while (oledbReader2.Read())
{
try
{
counter += 1;
query = "insert into tblgeo_street ( autoid, street_id, language, country, city, streetname, zip) values (" + counter.ToString() +
" , " + oledbReader2.GetValue(0).ToString() +
" , 'NL', 23, " + oledbReader2.GetValue(4).ToString() +
" , '" + oledbReader2.GetValue(1).ToString().Replace('\'', '´') + "'" +
" , " + oledbReader2.GetValue(3).ToString() + ") ";
OleDbCommand cmd3 = new OleDbCommand(query, cn3);
WriteToFile(query);
cmd3.ExecuteNonQuery();
}
catch (Exception errorException)
{
actionSucceedded = false;
//eventLog1.WriteEntry("Open db threw exception " + errorException.Message);
WriteToFile("insert tblgeo_street threw exception " + errorException.Message);
}
}
}
}

SQL Server 2012 : Between issue with parameters

I am having an issue with the query below:
SELECT
tT.RequestID,
TStatus,
TLead,
RequestDate,
tG.Category,
tETM.RAgency,
ECost,
tTT.TType
FROM
tT AS tT
INNER JOIN
tTMain AS tETM ON tT.RequestID = tETM.RequestID
INNER JOIN
tTType AS tTT ON tETM.AMod = tTT.TypeID
INNER JOIN
tGup AS tG ON tT.Category = tG.CategoryID
WHERE
tT.active = 1
AND (ApproxDate BETWEEN '09/30/2016' AND '09/30/2017')
AND tT.Category = 3
I am currently getting an error:
Conversion failed when converting date and/or time from character string.
The way I populate the above query in code:
string theQ = "SELECT " +
"tT.RequestID, " +
"TStatus, " +
"TLead, " +
"RequestDate, " +
"tG.Category, " +
"tETM.RAgency, " +
"ECost, " +
"tTT.TType " +
"FROM " +
"tT AS tT " +
"INNER JOIN " +
"tTMain AS tETM " +
"ON " +
"tT.RequestID = tETM.RequestID " +
"INNER JOIN " +
"tTType AS tTT " +
"ON " +
"tETM.AMod = tTT.TypeID " +
"INNER JOIN " +
"tGup AS tG " +
"ON " +
"tT.Category = tG.CategoryID " +
"WHERE " +
"tT.active = #val1 " +
"AND " +
"(ApproxDate BETWEEN #val2 AND #val3) " +
"AND " +
"tT.Category = #val4"
//Split up the between check. (it looks like this: BETWEEN 'xx/xx/xxxx' AND 'xx/xx/xxxx')
string[] betweenSplit = Regex.Split(Session["between"].ToString(), " AND ");
SqlDataAdapter da = new SqlDataAdapter();
DataSet _ds1 = new DataSet();
command = new SqlCommand(theQ, con);
command.Parameters.AddWithValue(1, "1");
command.Parameters.AddWithValue(2, betweenSplit[0].Replace(" BETWEEN ", ""));
command.Parameters.AddWithValue(3, betweenSplit[1]);
command.Parameters.AddWithValue(4, Session["UCat"].ToString());
da = new SqlDataAdapter(command);
da.Fill(_ds1, dbName);
da.Dispose();
closeAllConnections();
command.Parameters.Clear();
The error occurs on the line:
da.Fill(_ds1, "tripData");
What would I be doing incorrectly because the same query above works just fine when running it in Server Management Studio?
I suggest to avoid implicit conversion of date to/from string.
In your case it could be (for example):
CONVERT (datetime, '09/30/2016',101)
You should pass Datetime parameter to SQL like that
var yourFromDate = DateTime.Now;
SqlParameter fromDate = new SqlParameter("#val2", SqlDbType.DateTime) {Value = yourFromDate};
command.Parameters.Add(fromDate);

Postgresql Npgsql.PostgresException in c#

I have a problem with cmd.ExecuteReader() i get a Npgsql.PostgresException
public void connectDB()
{
try
{
server = "localhost";
database = "DoveVer3";
uid = "admin";
password = "admin";
string connectionString;
connectionString = "Host=" + server + ";Username =" + uid + ";" + "PASSWORD=" + password + ";DATABASE=" + database;
connection.ConnectionString = connectionString;
connection.Open();
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
}
I get the Exeption in the code below:
public void AddDoveToDB(Dove dove)
{
//add new dove record to tableDB
connectDB();
cmd = new NpgsqlCommand();
cmd.Connection = connection;
cmd.CommandText = "SELECT * FROM " + DoveTableDB + " WHERE `" + DoveIdColumnDoveTable + "` = '" + dove.GetDoveId() + "'";
NpgsqlDataReader rdr = cmd.ExecuteReader(); //// <<<<< HERE
if (rdr.Read() != true)
{
rdr.Close();
cmd.Parameters.Clear();
cmd.CommandText = "INSERT INTO " + DoveTableDB + "(" + DoveIdColumnDoveTable + "," + DoveIdFatherColumnDoveTable + "," + DoveIdMotherColumnDoveTable + "," + DoveEyesColorColumnDoveTable + "," + DoveFeatherColorDoveTable + "," + DoveImageNameColumnDoveTable + "," + DoveSexColumnDoveTable +") VALUES ('" + dove.GetDoveId() + "','" + dove.GetDoveFatherId() + "','" + dove.GetDoveMotherId() + "','" + dove.GetEyesColor() + "','" + dove.GetFeathersColor()+ "','" + dove.GetImageName() + "','" + dove.GetSex()+ "')";
cmd.ExecuteNonQuery();
}
connection.Close();
}
My database is called DoveVer3 and my schema DoveSchema here is my table code:
Name: DoveTable; Type: TABLE; Schema: DoveSchema; Owner: admin
--
CREATE TABLE "DoveTable" (
"doveId" character varying(20)[] NOT NULL,
"doveFather" character varying(20)[],
"doveMother" character varying,
"doveEyesColor" character varying(20)[],
"doveFeathersColor" character varying(20)[],
"doveSex" smallint DEFAULT 3 NOT NULL,
"imageName" character varying(30)
);
ALTER TABLE "DoveTable" OWNER TO admin;
The Exceptions Base messege:
relation "dovetable" don't exist; Statemants: {SELECT * FROM DoveTable
WHERE doveId = 'Test'}
By default all identifiers passed to PostgreSQL will be considered lower-case. Based on your creation script you used a quoted-identifer when defining your table so the following is required when using the name of your table.
SELECT * FROM "DoveTable"
Notice that it is wrapped in double quotes and the 'D' and 'T' are both capitalized. When using quoted-identifiers you must always write them out exactly the way you defined them.

MySqlDataAdapter Update table that uses Inner Join

I'm tring to add the Insert, Update and Delete commands to a MySqlDataAdapter which has the data added to it with the command:
//iec211.4521studenti
string lv_sObsTable = "`" + mv_sDatabase + "`.`" + mv_sGroup + "observatii`";
string lv_sStudTable = "`" + mv_sDatabase + "`.`" + mv_sGroup + "studenti'";
string lv_sObservatiiCommand = "SELECT o.idObservatie, o.idStudent, s.nume, o.observatie, o.lastUpdate FROM " + lv_sObsTable + " o INNER JOIN " + lv_sStudTable + " s USING (idStudent) ORDER BY s.nume ASC";
mv_dtAdapterObservatii = new MySqlDataAdapter(lv_sObservatiiCommand, mv_sqlConnection);
mv_dtAdapterObservatii.Fill(mv_dsTables, lv_sCurrentTable);
I've serched for an answer and I've found two possible solutions for UPDATE, but both of them give me an error:
string lv_sObsTB = "`" + mv_sDatabase + "`.`" + mv_sGroup + "observatii`";
string lv_sStudTB = "`" + mv_sDatabase + "`.`" + mv_sGroup + "studenti`";
//VERSION 1
string lv_sCommand = "UPDATE o SET s.idStudent=#idStudent, o.observatie=#observatie FROM " + lv_sObsTB + " AS o INNER JOIN " + lv_sStudTB + " s ON o.idStudent=s.idStudent ";
MySqlCommand lv_sqlCommand = new MySqlCommand(lv_sCommand);
lv_sqlCommand.Parameters.Add("#idStudent", MySqlDbType.Int16, 10, "idStudent");
lv_sqlCommand.Parameters.Add("#observatie", MySqlDbType.VarChar, 255, "observatie");
mv_dtAdapterObservatii.UpdateCommand = lv_sqlCommand;
//VERSION 2
string lv_sCommand = "UPDATE " + lv_sObsTB + " SET " + "idStudent=#" + lv_sStudTB + ".idStudent, observatie=#observatie WHERE idObservatie=#idObservatie AND " + lv_sObsTB + ".idStudent IN (SELECT " + lv_sStudTB + ".idStudent FROM " + lv_sStudTB + ")";
MySqlCommand lv_sqlCommand = new MySqlCommand(lv_sCommand);
lv_sqlCommand.Parameters.Add("#" + lv_sStudTB + ".idStudent", MySqlDbType.Int16, 10, "idStudent");
lv_sqlCommand.Parameters.Add("#observatie", MySqlDbType.VarChar, 255, "observatie");
lv_sqlCommand.Parameters.Add("#idObservatie", MySqlDbType.Int16, 10, "idObservatie");
mv_dtAdapterObservatii.UpdateCommand = lv_sqlCommand;
The error message for the first version is : "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'FROM iec211.4521observatii ASS o INNER JOIN iec211.4521studenti s ON o.id' at line 1"
The error message for the second version is:You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '.4521studenti'.idStudenti, observatie='test' WHERE idObservatie=1 ANDiec211.' at line 1"
I don't know how to use the MySQL commands in combination with MySqlCommand and MySqlDataAdapter.
Until now I've used the following command to obtain data for my table:
string lv_sObservatiiCommand = "SELECT * FROM `" + mv_sDatabase + "`.`" + mv_sGroup + "observatii` ORDER BY idStudent ASC";
mv_dtAdapterObservatii = new MySqlDataAdapter(lv_sObservatiiCommand, mv_sqlConnection);
mv_dtAdapterObservatii.Fill(mv_dsTables, lv_sCurrentTable);
In combination with MySqlCommandBuilder to get the update command and the parameters that needed to be setted:
lv_sqlCommandBuilder = new MySqlCommandBuilder(mv_dtAdapterObservatii);
mv_dtAdapterObservatii.UpdateCommand = lv_sqlCommandBuilder.GetUpdateCommand();
Can someone please explain to me how to correctly add the insert, update and delete commands to a MySqlDataAdapter that contains an INNER JOIN between 2 tables ?
I know that each table must be in a different data adapter, and they are. The "4521studenti" table is inside "mv_dtAdapterStudenti", which is not included in the code above.
Thank you for the help and I hope this won't be considered as a bad post. :)
Okey. I think I've figured it out.
This is the SELECT command for 4521observatii:
string lv_sStudent = "`" + mv_sDatabase + "`.`" + mv_sGroup + "studenti`";
string lv_sObservatii = "`" + mv_sDatabase + "`.`" + mv_sGroup + "observatii`";
string lv_sObservatiiCommand = "SELECT o.idObservatie, o.idStudent, s.nume, o.observatie, o.lastUpdate FROM " + lv_sObservatii + " o INNER JOIN " + lv_sStudent + " s USING (idStudent) ORDER BY s.nume ASC";
// Read data from the server for the current table and add it to the DataSet
mv_dtAdapterObservatii = new MySqlDataAdapter(lv_sObservatiiCommand, mv_sqlConnection);
mv_dtAdapterObservatii.Fill(mv_dsTables, lv_sCurrentTable);
And this is the code for the UPDATE command, inside a different method:
// `iec211`.`4521observatii`
string lv_sObsTB = "`" + mv_sDatabase + "`.`" + mv_sGroup + "observatii`";
// `iec211`.`4521studenti`
string lv_sStudTB = "`" + mv_sDatabase + "`.`" + mv_sGroup + "studenti`";
string lv_sSelectStudenti = "(SELECT idStudent FROM " + lv_sStudTB + " WHERE idStudent=#idStudent)";
string lv_sCommand = "UPDATE " + lv_sObsTB + " SET idStudent="+ lv_sSelectStudenti + ", observatie=#observatie WHERE idObservatie=#idObservatie";
MySqlCommand lv_sqlCommand = new MySqlCommand(lv_sCommand);
lv_sqlCommand.Parameters.Add("#idStudent", MySqlDbType.Int16, 10, "idStudent");
lv_sqlCommand.Parameters.Add("#observatie", MySqlDbType.VarChar, 255, "observatie");
lv_sqlCommand.Parameters.Add("#idObservatie", MySqlDbType.Int16, 10, "idObservatie");
mv_dtAdapterObservatii.UpdateCommand = lv_sqlCommand;
mv_dtAdapterObservatii.UpdateCommand.Connection = mv_sqlConnection;
The idea is that when I use INNER JOIN I bring data from two different tables and put them together. When I used the UPDATE command, the program didn't know which table he was using and gived those errors.
So I thought what if I update the values of 4521observatii and for the column that is used as FOREIGN KEY I assign the value from 4521studenti.
I know it's like "Tell me your name so I can tell you your name.", but it worked for me.
I hope this will help others and you have a better and cleaner solution, pleas tell me :)

C# Insert and Update content to DataGridView do not work !

I got a really troublesome issue here, the query seems to be apparently corrent but it returns no rows of data...
Basically the issue is after an insert, I make a select to obtain the auto increment number (NAlbum) to a variable (I'm using C#), here's the piece of code that's troubling me
//Associar ID de Artista
ClassBD.DBMyReader(
"SELECT NArtista " +
"FROM Artistas " +
"WHERE (Nome = '" + CBBoxAddArtista.Text + "')");
ClassBD.myReader.Read();
temptabelas[0] = ClassBD.myReader.GetInt32(0);
//Associar ID da Editora
ClassBD.DBMyReader(
"SELECT NEditora " +
"FROM Editora " +
"WHERE (Nome = '" + CBBoxAddEditora.Text + "')");
ClassBD.myReader.Read();
temptabelas[1] = ClassBD.myReader.GetInt32(0);
//Associar ID da Media
ClassBD.DBMyReader(
"SELECT NMedia " +
"FROM Media " +
"WHERE (Nome = '" + CBBoxAddMedia.Text + "')");
ClassBD.myReader.Read();
temptabelas[2] = ClassBD.myReader.GetInt32(0);
//Associar ID do Genero
ClassBD.DBMyReader(
"SELECT NGenero " +
"FROM Genero_de_Musica " +
"WHERE (Nome = '" + CBBoxAddGenero.Text + "')");
ClassBD.myReader.Read();
temptabelas[3] = ClassBD.myReader.GetInt32(0);
ClassBD.DBMyInsertCommand("INSERT INTO Albuns " +
"(NArtista, NEditora, NGeneroDeMusica, NMedia, Nome, [Ano de Edição])" +
"VALUES (" + temptabelas[0] + "," + temptabelas[1] + "," + temptabelas[2] + "," + temptabelas[3] + ",'" + TxtAddMusicaAlbum.Text + "'," + int.Parse(TxtAddAnoEdicao.Text) + ")");
ClassBD.DBMyReader("SELECT MAX(NAlbum) AS Actual " +
"FROM Albuns");
tempnalbum = ClassBD.myReader.GetInt32(0);
musicasBindingSource.Filter = "NAlbum = " + tempnalbum;
Thanks in advance,
Luis Da Costa
1st. You Need to parametized your query for cleaner syntax.
Example:
string CommandText = "select NArista from Artista where Nome=#Nome";
cmd = new SqlCommand(CommandText);
cmd.Connection = con;
cmd.Parameters.AddWithValue("#Nome",CBBoxAddArtista.Text);
rdr = cmd.ExecuteReader();
while(rdr.Read())
{
temptabelas[0] = rdr["NAtista"].ToString()
}
After Getting the Result loaded to Data gridview then loop all the values
Then use your insert statement.
Example:
foreach (DataGridViewRow dr in Datagridview1.Rows)
{
//Do your Code
"INSERT INTO Albuns " +
"(NArtista, NEditora, NGeneroDeMusica, NMedia, Nome, [Ano de Edição])" +
"VALUES (#1,#2,#3,#4,#5,#6)";
// Add parameter
cmd.Parameters.AddWithValue("#1",(string) dr.Cells["Natista"].Value.ToString());
.
.
.
.
cmd.Parameters.AddWithValue("#6",int.Parse(TxtAddAnoEdicao.Text)
cmd.ExecuteNonQuery();
}
HI Everyone,
ClassBD.DBMyInsertCommand("INSERT INTO Albuns " +
"(NArtista, NEditora, NGeneroDeMusica, NMedia, Nome, [Ano de Edição]) " +
"VALUES (" + temptabelas[0] + "," + temptabelas[1] + "," + temptabelas[2] + "," + temptabelas[3] + ",'" + TxtAddMusicaAlbum.Text + "'," + int.Parse(TxtAddAnoEdicao.Text) + ")");
OleDbConnection connection = new OleDbConnection(ClassBD.MyConnectionString);
connection.Open();
OleDbCommand MyCommand = new OleDbCommand("SELECT NAlbum FROM Albuns WHERE (Nome = #Nome)", connection);
MyCommand.Parameters.AddWithValue("#Nome", TxtAddMusicaAlbum.Text);
OleDbDataReader myReader = MyCommand.ExecuteReader(CommandBehavior.CloseConnection);
ClassBD.tempnalbum = myReader.GetInt32 ;
"Hi, I've asked this very question yesterday, you told me to parameterize the query, and so I did... However, it still comes up with no rows... Help?"
"(The Insert is correct, I've checked it's entry)
Private Sub BoundLoadButton_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs)
Handles BoundLoadButton.Click
swatch.Reset()
swatch.Start()
Cursor = Cursors.WaitCursor
Try
Using BoundObject As New UnboundClass(mMySQLConnectionString)
Call BoundObject.BoundDataLoading(UnboundDataGridView, _
RecordCountTextBox, _
mErrorMsgString)
If Not IsNothing(mErrorMsgString) Then
Cursor = Cursors.Default
MessageBox.Show(mErrorMsgString, _
Me.Text, _
MessageBoxButtons.OK, _
MessageBoxIcon.Error)
End If
End Using
Catch exError As Exception
MessageBox.Show(exError.Message, _
Me.Text, _
MessageBoxButtons.OK, _
MessageBoxIcon.Error)
End Try
Cursor = Cursors.Default
swatch.Stop()
mTimeDouble = swatch.ElapsedMilliseconds * 0.001
BoundTimeTextBox.Text = mTimeDouble.ToString
End Sub

Categories

Resources