SQL unable to cast object of type 'system.string' to type 'system.iformatprovider' error in vb.net - sql

I am trying to run this Query in my VB Application but receive an error saying:
unable to cast object of type 'system.string' to type 'system.iformatprovider'
SQL = "insert into billing_pdf_archive (reseller_sequence, invoice_number, pdf, worddoc, csv_cdr_file, csv_services_file, sub_total, vat_amount, grand_total, invoice_type, directdebit) values ('" + reseller.ToString + "','" + invoice_number.ToString + "', '" + Replace(reseller_company_name + "-" + invoice_number + ".pdf", " ", "_") + "', '" + Replace(reseller_company_name + "-" + invoice_number + ".doc", " ", "_") + "', '" + Replace(reseller_company_name + "-" + invoice_number.ToString + "_CDR.xlsx", " ", "_") + "', '" + Replace(reseller_company_name + "-" + invoice_number.ToString + "_Services.xlsx", " ", "_") + "', " + total.ToString("F2") + ", " + vat_amount.ToString("F2") + ", " + grand_total.ToString("F2") + ", 'Month End Reseller', '" + customer_direct_debit + "')"
conn3.ConnectionString = "server=" + global_variables.web_server_ip + "; user id=" + global_variables.web_server_username + "; password=" + global_variables.web_server_password + "; database=" + global_variables.web_server_database + "; "
conn3.Open()
myCommand3.Connection = conn3
myCommand3.CommandText = SQL
myCommand3.ExecuteNonQuery()
conn3.Close()

This is not a complete answer but I'll post it as an answer so that I can post formatted code. If you do as suggested in the comments and write clean, readable code then it will become obvious where the issue is and how to fix it. When you have one line that does lots of different things then working out what on that line is causing an issue is all but impossible. You should use an XML literal for your SQL code, parameters for your values and a connection string builder, e.g.
Dim sql = <sql>
INSERT INTO MyTable
(
Column1,
Column2
)
VALUES
(
#Column1,
#Column2
)
</sql>
command.CommandText = sql.Value
command.Parameters.AddWithValue("#Column1", value1)
command.Parameters.AddWithValue("#Column2", value2)
Dim builder As New SqlConnectionStringBuilder
builder.DataSource = server
builder.InitialCatalog = database
connection.ConnectionString = builder.ConnectionString
Now you'll be able to see exactly what part of your code is causing the issue and, if you still can't solve it yourself, will be able to point out where the issue is to us instead of expecting us to read that dog's breakfast.

Related

Needs to handle the names which has a quotation inside

I have two queries which inserts and updates the DB-
insertSQL = "insert into LineManager(LINEMANAGERID,LINEMANAGERNAME,BUSINESSGROUPID,STATUS) VALUES('" + lineManager.getLineManagerID() + "','" + lineManager.getLineManagerName() + "','" + lineManager.getBusinessGroupID() + "','" + lineManager.getStatus() + "')";
updateSQL = "update LineManager set BUSINESSGROUPID ='" + lineManager.getBusinessGroupID() + "' , LINEMANAGERNAME ='" + lineManager.getLineManagerName() + "' , STATUS ='" + lineManager.getStatus() + "' where LINEMANAGERID='" + lineManager.getLineManagerID() + "'";
so far it was working fine for the regular names, but it is facing issues when the LineManager name is like -'Doko N'dah, Mr. Dominick'. It's throwing exceptions during execution.
Can anybody help to resolve this issue?
Use bind variables:
QSqlQuery query;
query.prepare("insert into LineManager(LINEMANAGERID,LINEMANAGERNAME,BUSINESSGROUPID,STATUS) VALUES(:id,:name,:groupid:status)");
query.bindValue( ":id", lineManager.getLineManagerID() );
query.bindValue( ":name", lineManager.getLineManagerName() );
query.bindValue( ":groupid", lineManager.getBusinessGroupID() );
query.bindValue( ":status", lineManager.getStatus() );
query.exec();

VB 2010 INSERT INTO syntax error

Hello Good Afternoon I have a program in VB.Net that will Input data
from textboxes into Access Database here is sample image
This is the code I am using and it gives me an error
m = TextBox1.Text
b = "'" + TextBox2.Text + "'"
x = "'" + TextBox3.Text + "'"
d = TextBox4.Text
n = "'" + TextBox5.Text + "'"
Dim s2 As String
s2 = "insert into users2 ( num , name1 , pass , add , phone ) " & " values ( " + m + " , " + n + " , " + b + " , " + x + " , " + d + " ) "
Dim cmd2 As New OleDbCommand(s2, con)
cmd2.ExecuteNonQuery()
Looking forward that someone will enlighten my problem since its im starting to program.
TYSM for future help
You need to encapsulate values you want to insert into ''
. "values('" + m + "', '" + ...
2 I don't understand & operator between two parts of query in the beginning

eception Unclosed quotation mark after the character string . But i have no idea why

I seem to be getting an exception which reads "Incorrect syntax near '00'.
Un-closed quotation mark after the character string ',False )'." what am i doing wrong? It's so hard for me to spot small errors like this. Any help would be appreciated. Thank you in advance.
A bit more detail: I'm using visual studio and SQL server if that helps to narrow down the problem?
SqlConnection conn = Database.GetConnection();
SqlCommand command ;
SqlDataAdapter adpter = new SqlDataAdapter();
DataSet ds = new DataSet();
XmlReader xmlFile ;
string sql = null;
int PatientNo=0;
bool FurtherVisitRequired;
string AdvisoryNotes=null;
string Prescription=null;
string TreatmentProvided=null;
DateTime ActualVisitDateTime;
string Priority=null;
DateTime ScheduledDateTime;
string TreatmentInstructions=null;
int MedicalStaffID;
string VisitRefNo=null;
//conn = new SqlConnection(conn);
xmlFile = XmlReader.Create("\\HomeCareVisit.xml", new XmlReaderSettings());
ds.ReadXml(xmlFile);
int i = 0;
conn.Open();
for (i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)
{
VisitRefNo=ds.Tables[0].Rows[i].ItemArray[0].ToString();
PatientNo= Convert.ToInt32(ds.Tables[0].Rows[i].ItemArray[1]);
ScheduledDateTime = Convert.ToDateTime(ds.Tables[0].Rows[i].ItemArray[2]);
TreatmentInstructions = ds.Tables[0].Rows[i].ItemArray[3].ToString();
MedicalStaffID= Convert.ToInt32(ds.Tables[0].Rows[i].ItemArray[4]);
Priority = ds.Tables[0].Rows[i].ItemArray[5].ToString();
ActualVisitDateTime = Convert.ToDateTime(ds.Tables[0].Rows[i].ItemArray[6]);
TreatmentProvided = ds.Tables[0].Rows[i].ItemArray[7].ToString();
Prescription = ds.Tables[0].Rows[i].ItemArray[8].ToString();
AdvisoryNotes = ds.Tables[0].Rows[i].ItemArray[9].ToString();
FurtherVisitRequired =Convert.ToBoolean(ds.Tables[0].Rows[i].ItemArray[10]);
sql = "insert into HomeCareVisit values(" + VisitRefNo + ",'" + PatientNo + "'," + ScheduledDateTime + "" + TreatmentInstructions + ",'" + MedicalStaffID + "'," + Priority+ "'," + ActualVisitDateTime + ",'" + TreatmentProvided + "'," + Prescription+ "',"+AdvisoryNotes +"',"+FurtherVisitRequired+" )";
command = new SqlCommand(sql, conn);
adpter.InsertCommand = command;
adpter.InsertCommand.ExecuteNonQuery();
}
conn.Close();
MessageBox.Show("Done .. ");
Icemand answered the original question. But his answer has brought a new one. How do you turn the identity insert on and off in the SQL command?
You missed some quotation marks and commas in the following line:
sql = "insert into HomeCareVisit values(" + VisitRefNo + ",'" + PatientNo + "'," + cheduledDateTime + "" + TreatmentInstructions + ",'" + MedicalStaffID + "'," + Priority+ "'," + ActualVisitDateTime + ",'" + TreatmentProvided + "'," + Prescription+ "',"+AdvisoryNotes +"',"+FurtherVisitRequired+" )";
The missing quotation marks are around the ScheduledDateTime, Perescription, AdvisoryNotes, TreatmentInstructions, etc. values. You should put quotation marks around the string and datetime variables and you should not put for numbers. The correct code should be:
sql = "insert into HomeCareVisit values(" + VisitRefNo + ",'" + PatientNo + "','" + ScheduledDateTime + "','" + TreatmentInstructions + "','" + MedicalStaffID + "','" + Priority+ "','" + ActualVisitDateTime + "','" + TreatmentProvided + "','" + Prescription+ "','"+AdvisoryNotes +"',"+FurtherVisitRequired+" )";
I suggest that you should check your variables type and put the marks around the mentioned variables + take a look on each comma if they are in the right place or they are missing. To make a double check print out the query string before you send it ot the DB that will help you debug your code.
You are not using parameters, and you are not replacing values that contain the string delimiter "'".
You should replace apostrophs in strings, like for example TreatmentProvided.Replace("'", "''").
And you shouldn't build a string in the first place.
Use parameters.
PS:
You can get it to work with an idendity like this:
SET IDENTITY_INSERT [dbo].[HomeCareVisit] ON
-- insert here:
insert into HomeCareVisit VALUES (" + VisitRefNo + ",'" + PatientNo + "','" + ScheduledDateTime + "','" + TreatmentInstructions + "','" + MedicalStaffID + "','" + Priority+ "','" + ActualVisitDateTime + "','" + TreatmentProvided + "','" + Prescription+ "','"+AdvisoryNotes +"',"+FurtherVisitRequired+" )
-- end insert
SET IDENTITY_INSERT [dbo].[HomeCareVisit] OFF
Also, if you are writing table-content back into a database, you can read the xml into a datatable, and then use BulkInsert.

SQL Inner Join query returns no results

I'm refactoring a Java program written by someone else a couple of years ago, can't get in contact with them to find out anything about the SQL / database, but this query is not working (not returning any results when having two queries separately does). I know it's annoying to ask without more info, but I haven't really got much choice at the moment.
"SELECT " + CLMHDR + ".POLBRC, "
+ CLMHDR + ".POLTYC, " + CLMHDR + ".POLNOC," + CLMHDR + ".CLTKYC, "
+ POLHDR + ".INCPTP FROM "+ CLMHDR +
"INNER JOIN " + POLHDR + " ON " + CLMHDR + ".CLTKYC = " + POLHDR+ ".CLTKYP"
+ " WHERE POLNOC = "+ polnocSearch
+ " AND POLBRC = '" + polbrcSearch + "'"
+ " AND POLTYC = '" + poltycSearch + "'"
+ " AND DATRPC <= " + claimDate
+ " GROUP BY POLBRC, POLTYC, POLNOC, CLTKYC"
The tables CMLHDR and POLHDR do contain the columns it is referencing, and CLTKYC and CLTKYP are keys in each table. Sorry about the horrible names, we're stuck with RPG as well.
Edit:
What does work is this:
"SELECT POLBRC, POLTYC, POLNOC, CLTKYC FROM "+ CLMHDR
+ " WHERE POLNOC = "+ polnocSearch
+ " AND POLBRC = '" + polbrcSeach + "'"
+ " AND POLTYC = '" + poltycSearch + "'"
+ " AND DATRPC <= " + claimDate
+ " GROUP BY POLBRC, POLTYC, POLNOC, CLTKYC"
followed by this:
"SELECT INCPTP, TRMTHP FROM "+ POLHDR + " WHERE POLNOP = "+ polnocSearch
+ " AND POLBRP = '"+ polbrcSearch+ "' AND POLTYP = '"+ poltycSearch + "'"
but I'd really prefer all the data to be returned at once.
There is a space missing between the FROM and the INNER JOIN clause:
FROM "+ CLMHDR +
"INNER JOIN
It is should be this:
FROM "+ CLMHDR +
" INNER JOIN
In addition to the inner join problem, you have an issue with the group by. It should have INCPTP. In any database except for MySQL, this will generate an error.
By the way, it would be easier to answer your question if it included two things:
The database engine you are using
The resulting query string with the values filled in

string concatation in sql query

i am having confusion with this string concatenation
could some body please brief me how this string concatenation taking place?
The confusion i am having is that, how this +, "", ' are working in this
int i = Magic.Allper("insert into tbl_notice values ('" + Label1.Text + "','" + companyTxt.Text + "','" + txtBranch.Text + "','" + dateTxt.Text + "' ,'" + reportingTxt.Text + "','" + venueTxt.Text + "','" + eligibilityTxt.Text + "')");
Anything between two " characters is taken as a String in Java so "','" produces ','. SQL requires Strings wrapped in '. So "'" + venueTxt.Text + "'" parses to 'variable value' when the query is made.
("insert into tbl_notice values ('" + Label1.Text + "','" + companyTxt.Text + "','" + txtBranch.Text + "','" + dateTxt.Text + "' ,'" + reportingTxt.Text + "','" + venueTxt.Text + "','" + eligibilityTxt.Text + "')");
Assuming that
Label1= Hello
companyTxt = ABC
txtBranch = Engineering
dateTxt = 2010-12-01
reportingTxt = Fergusson
venueTxt = Batcave
eligibilityTxt = No
The above values are replaced in the SQL statement, making it look like
("insert into tbl_notice values ('" + Hello + "','" + ABC + "','" + Engineering + "','" + 2010-12-01 + "' ,'" + Fergusson + "','" + Batcave + "','" + No + "')");
The "+" operator joins the string values, resulting in
("insert into tbl_notice values ('Hello','ABC','Engineering','2010-12-01' ,'Fergusson','Batcave','No')")
I strongly recommend that you don't use string concatenation in SQL queries. They provoque SQL injections. This will cause security issues.
What is SQL Injection?
In response to your question, this concatenation simply takes every TextBox.Text property value and concatenate it into your insert statement.
I strongly recommend that you're using parameterized queries using ADO.NET lise the following example (assuming SQL Server):
using (var connection = new SqlConnection(connString))
using (var command = connection.CreateCommand()) {
string sql = "insert into tbl_notice values(#label1, #companyTxt, #txtBranch, #dataTxt, #reportingTxt, #venueTxt, #eligibilityTxt)";
command.CommandText = sql;
command.CommandType = CommandType.Text;
SqlParameter label1 = command.CreateParameter();
label1.ParameterName = "#label1";
label1.Direction = ParameterDirection.Input;
label1.Value = Label1.Text;
SqlParameter companyTxt = command.CreateParameter();
companyTxt.ParameterName = "#companyTxt";
companyTxt.Direction = ParameterDirection.Input;
companyTxt.Value = companyTxt.Text;
// And so forth for each of the parameters enumerated in your sql statement.
if (connection.State == ConnectionState.Close)
connection.Open();
int rowsAffected = command.ExecuteNonQuery();
}
I would use the string.Format method for clarity
int i = Magic.Allper(string.Format("insert into tbl_notice values ('{0}','{1}','{2}','{3}','{4}','{5}','{6}')",
Label1.Text,
companyTxt.Text,
txtBranch.Text,
dateTxt.Text,
reportingTxt.Text,
venueTxt.Text,
eligibilityTxt.Text));
You might also want to create an extension method that will make sure the strings are safe to pass to SQL in this fashion
public static string ToSqlFormat(this string mask, params string[] args)
{
List<string> safe = args.ToList();
safe.ForEach(a => a.Replace("'", "''"));
return string.Format(mask, safe);
}
which will let you write
string insert = "insert into tbl_notice values ('{0}','{1}','{2}','{3}','{4}','{5}','{6}')";
int i = Magic.Allper(insert.ToSqlFormat(
Label1.Text,
companyTxt.Text,
txtBranch.Text,
dateTxt.Text,
reportingTxt.Text,
venueTxt.Text,
eligibilityTxt.Text));