I have a loop in which I grab certain ID's to make a call in a database. There are 2 variables within the query.
The first one works fine but the second one returns nothing. I have tested it a lot and know that the correct value is coming through to the query. Not sure what I am doing wrong here. I replace the variable with a hard coded value that I know is returning and it works fine.
Here is my code:
SqlDataAdapter d8;
d8 = new SqlDataAdapter("SELECT SUM(CAST(AMOUNT AS BIGINT)) AS NEW_AMOUNT
FROM ddb_proc_log_base
WHERE (PROVID = " + docId +
" AND CHART_STATUS = 90
AND YEAR(PLDATE) = 2016
AND CLASS = 2
AND ORD = " + defer + ") OR (ORD = " + defer +
" AND PROVID = " + this.getDocHygDS.Tables[0].Rows[t]["HYG_ID"] +
" AND CHART_STATUS = 90
AND YEAR(PLDATE) = 2016 AND CLASS = 2)", conn3);
cmdBuilder5 = new SqlCommandBuilder(d8);
d8.Fill(this.balances);
#Tyler Nichol You are missing the a single quote where you concatenate string value like
Example ORD = '" + defer + "'
below is an example:
try{
"select * from SomeTable where name='"+name+","
// in your case this may like the following
d8 = new SqlDataAdapter("select SUM(CAST(AMOUNT AS BIGINT)) AS NEW_AMOUNT
FROM ddb_proc_log_base where ( PROVID = "+docId+" AND CHART_STATUS = 90
AND YEAR(PLDATE) = 2016 AND CLASS = 2 AND ORD = '" + defer + "') OR (ORD = '"
+ defer + "' AND PROVID = " + this.getDocHygDS.Tables[0].Rows[t]["HYG_ID"]
+ " AND CHART_STATUS = 90 AND YEAR(PLDATE) = 2016 AND CLASS = 2)", conn3);
}
catch(Exception e)
{
//Throw Null Exception Here
}
Recommended Solution
try{
string UserName="John";
cmd.CommandText = "select * from SomeTable where name=#Name";
cmd.Parameters.AddWithValue("#Name", UserName);
}
catch(Exception e)
{
//Throw Null Exception Here
}
You need to use a CONTAIN in the query :
DataSet getDocHygDS = new DataSet();
string[] hyg_id = getDocHygDS.Tables[0].AsEnumerable().Select(x => x.Field<string>("HYG_ID")).Distinct().ToArray();
string or = "'" + string.Join("' OR '", hyg_id) + "'";
SqlDataAdapter d8;
string query = string.Format("SELECT SUM(CAST(AMOUNT AS BIGINT)) AS NEW_AMOUNT" +
" FROM ddb_proc_log_base" +
" WHERE (PROVID = {0}" +
" AND CHART_STATUS = 90" +
" AND YEAR(PLDATE) = 2016" +
" AND CLASS = 2" +
" AND ORD = {1})" +
" OR" +
" (ORD = {1}" +
" AND CONTAINS(PROVID, {2})" +
" AND CHART_STATUS = 90" +
" AND YEAR(PLDATE) = 2016 AND CLASS = 2)", docId, defer, or);
d8 = new SqlDataAdapter(query, conn3);
cmdBuilder5 = new SqlCommandBuilder(d8);
d8.Fill(this.balances);
Related
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);
I got this update thing i cant figure out. The save button seems to be working, its updating the table. I cant seem to figure out the SaveToStock method. It throws me this error:
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 ''90' at line 1
I tried putting a breakpoint, got this. Break data
Save button
protected void saveButton_Click(object sender, EventArgs e)
{
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
connection.Open();
MySQLParser parser = new MySQLParser(connection);
int nonsoldamount = 0;
if (parser.hasRows("SELECT * FROM dpf_stock WHERE geometry = '" + DropDownListGeometry.SelectedValue + "' AND length = '" + DropDownListLength.SelectedValue.Replace(',', '.') + "' AND CPSI = '" + DropDownListCPSI.SelectedValue + "'"))
{
nonsoldamount = Convert.ToInt32(parser.readSelectCommand("SELECT amount FROM dpf_stock WHERE geometry = '" + DropDownListGeometry.SelectedValue + "' AND length = '" + DropDownListLength.SelectedValue.Replace(',', '.') + "' AND CPSI = '" + DropDownListCPSI.SelectedValue + "'", "amount"));
if (editing)
{
oldamount = Convert.ToInt32(parser.readSelectCommand("SELECT amount FROM dpf_sale where dpfSaleID = " + IDdpfSale, "amount"));
nonsoldamount = nonsoldamount + oldamount;
}
if (nonsoldamount < Convert.ToInt32(TextBoxAmount.Text))
{
ErrorMessage.Controls.Add(new LiteralControl("<span class=\"error\">There are only " + nonsoldamount + " in stock with the selected attributes</span>"));
return;
}
}
else
{
ErrorMessage.Controls.Add(new LiteralControl("<span class=\"error\">There are 0 in stock with the selected attributes</span>"));
return;
}
string sql_query = "";
if (editing)
{
oldamount = Convert.ToInt32(parser.readSelectCommand("SELECT amount FROM dpf_sale where dpfSaleID = " + IDdpfSale, "amount"));
sql_query = "UPDATE dpf_sale SET orderNo = ?orderNo, fk_operatorID = ?operator, status = ?status, amount = ?amount, geometry = ?geometry, length = ?length, CPSI = ?CPSI " +
"WHERE dpfSaleID = ?IDdpfSale";
}
else
{
sql_query = "INSERT INTO dpf_sale (orderNo, fk_operatorID, amount, geometry, length, CPSI, status) " +
"VALUES (?orderNo, ?operator, ?amount, ?geometry, ?length, ?CPSI, ?status)";
}
MySqlCommand myCommand = new MySqlCommand(sql_query, connection);
myCommand.Parameters.AddWithValue("?IDdpfSale", IDdpfSale);
myCommand.Parameters.AddWithValue("?orderNo", TextBoxOrderNo.Text);
myCommand.Parameters.AddWithValue("?operator", DropDownListOperator.SelectedValue);
myCommand.Parameters.AddWithValue("?geometry", DropDownListGeometry.SelectedValue);
myCommand.Parameters.AddWithValue("?length", DropDownListLength.SelectedValue.Replace(',', '.'));
myCommand.Parameters.AddWithValue("?status", DropDownListStatus.SelectedValue);
myCommand.Parameters.AddWithValue("?CPSI", DropDownListCPSI.SelectedValue);
myCommand.Parameters.AddWithValue("?amount", TextBoxAmount.Text);
myCommand.ExecuteNonQuery();
saveToStock();
}
editing = false;
IDdpfSale = 0;
Response.Redirect("dpf_sale.aspx");
}
Stock Change
private void saveToStock()
{
connection = new MySqlConnection(connectionString);
parser = new MySQLParser(connection);
connection.Open();
string sql_stock = "";
string sql_log = "";
int newsaleID;
if (editing == true)
{
sql_stock = "UPDATE dpf_stock SET amount = amount + " + oldamount + " - " + TextBoxAmount.Text + " WHERE geometry = '" + DropDownListGeometry.SelectedValue + "' AND length = '" + DropDownListLength.SelectedValue.Replace(',', '.') + "' AND CPSI = '" + DropDownListCPSI.SelectedValue;
sql_log = "UPDATE dpf_stock_log SET amount = " + TextBoxAmount.Text + " WHERE sale = 1 and id = " + IDdpfSale;
}
else
{
newsaleID = Convert.ToInt32(parser.readSelectCommand("SELECT MAX(dpfSaleID) id FROM dpf_sale", "id"));
sql_log = "INSERT INTO dpf_stock_log (id, assembly, sale, amount) VALUES (" + newsaleID + ", 0, 1, " + TextBoxAmount.Text + ")";
if (parser.hasRows("SELECT * FROM dpf_stock WHERE geometry = '" + DropDownListGeometry.SelectedValue + "' AND length = '" + DropDownListLength.SelectedValue.Replace(',', '.') + "' AND CPSI = '" + DropDownListCPSI.SelectedValue + "'"))
{
sql_stock = "UPDATE dpf_stock SET amount = amount - " + TextBoxAmount.Text + " WHERE geometry = '" + DropDownListGeometry.SelectedValue + "' AND length = '" + DropDownListLength.SelectedValue.Replace(',', '.') + "' AND CPSI = '" + DropDownListCPSI.SelectedValue;
}
else
{
return;
}
}
MySqlCommand myCommand1 = new MySqlCommand(sql_stock, connection);
myCommand1.ExecuteNonQuery();
MySqlCommand myCommand2 = new MySqlCommand(sql_log, connection);
myCommand2.ExecuteNonQuery();
connection.Close();
}
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);
I want to ask why query return null and not update what i want. Sorry I'm still new with asp.net and c#
myquery = "UPDATE kenderaan SET buatan = " + "'" + carmake + "'" + "," +
"model = " + "'" + carmodel + "'" + "," +
"no_enjin = " + "'" + carenjin + "'" + "," +
"cc = " + carcc + "," +
"seatCapacity = " + carseat + "," +
"tahunBuatan = " + caryear + " WHERE no_kenderaan = " + "'" + carid + "'" + "," +
"AND ic = " + "'" + cusid + "'";
connection = new DbConnection();
connection.Update(myquery);
restructure your code into this, use Connection object, Command Object, using statement.
string myquery = "UPDATE kenderaan SET buatan = #carmake ," +
" model = #carmodel ," +
" no_enjin = #carenjin ," +
" cc = #carcc ," +
" seatCapacity = #carseat ," +
" tahunBuatan = #caryear " +
"WHERE no_kenderaan = #carid " +
" AND ic = #cusid ";
using (MySqlConnection _conn = new MySqlConnection("connectionStringHere"))
{
using (MySqlCommand _comm = new MySqlCommand())
{
_comm.Connection = _conn;
_comm.CommandText = myquery;
_comm.CommandType = CommandType.Text;
_comm.Parameters.AddWithValue("#carmake",carmake);
_comm.Parameters.AddWithValue("#carmodel",carmodel);
_comm.Parameters.AddWithValue("#carenjin",carenjin);
_comm.Parameters.AddWithValue("#carcc",carcc);
_comm.Parameters.AddWithValue("#carseat",carseat);
_comm.Parameters.AddWithValue("#caryear",caryear);
_comm.Parameters.AddWithValue("#carid",carid);
_comm.Parameters.AddWithValue("#cusid",cusid);
try
{
_conn.Open();
_comm.ExecuteNonQuery();
MessageBox.Show("Updated!");
}
catch (MySqlException e)
{
MessageBox.Show(e.ToString()); // as mentioned on the comment
}
}
}
Reasons why you need to parameterized your query:
avoids SQL Injection
makes your code more readable
etc.. :D
Sources
AddWithValue
Add (recommended and leaving you this as an assignment :D)
Create a DbCommand to execute the Update statement by using ExecuteNonQuery() method. If you are using SQL Server then you can use this piece of code snippet:
using System.Data.SqlClient;
string query = "UPDATE kenderaan SET buatan = #carmake" +
", model = #carmodel" +
", no_enjin = #carenjin" +
", cc = #carcc" +
", seatCapacity = #carseat" +
", tahunBuatan = #caryear" +
" WHERE no_kenderaan = #carid AND ic = #cusid";
using (SqlConnection conn = new SqlConnection("<connection string>"))
{
using (SqlCommand cmd = new SqlCommand(query, conn))
{
cmd.Parameters.AddWithValue("#carmake", carmake);
cmd.Parameters.AddWithValue("#carmodel", carmodel);
cmd.Parameters.AddWithValue("#carenjin", carenjin);
cmd.Parameters.AddWithValue("#carcc", carcc);
cmd.Parameters.AddWithValue("#carseat", carseat);
cmd.Parameters.AddWithValue("#caryear", caryear);
cmd.Parameters.AddWithValue("#carid", carid);
cmd.Parameters.AddWithValue("#cusid", cusid);
conn.Open();
cmd.ExecuteNonQuery();
}
}
Try this code in place of your code:
and make sure that varchar parameters are compare to string values.
string myquery = "UPDATE kenderaan SET buatan = '" + carmake + "',model = '"+
carmodel + "',no_enjin = '" +carenjin + "',cc = " + carcc + ",seatCapacity = " +
carseat + ",tahunBuatan = " + caryear +
" WHERE no_kenderaan = '" + carid + "' AND ic = '" + cusid + "'";
connection = new DbConnection();
connection.Update(myquery);
UPDATED: Apologize, I had just corrected your query with your where condition I just removed comma which you used to separate two condition.
To avoid SQL Injection Attacks, Use one of these :
1) Parameters with Stored Procedures
2) Use Parameters with Dynamic SQL
3) Constrain Input
you can find more information over HERE
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