System.Data.SqlClient.SqlException (0x80131904): Incorrect syntax near ')' - sql-server

I have been trying to debug a piece of code and I have been thus far very unsuccessful in doing this.
I keep on getting this error
System.Data.SqlClient.SqlException (0x80131904): Incorrect syntax near ')'
and I can't seem to see where the error is.
The code is below, having looked at various answers on this site and looked at the examples. The situation is that I am writing a program that accesses a database and is able to add and save data to that database. It is located on a server - though this is on my laptop.
I have written, re-written and copied the connection string to ensure there are no mistakes in it and even dropped a copy of the string into word and compared it to the one that is in the coding itself but to no avail.
public partial class AddingClients : Form
{
public AddingClients()
{
InitializeComponent();
}
String CompanyName2;
String ClientName2;
String CompanyAddress12;
String CompanyAddress22;
String CompanyAddress32;
String CompanyTown2;
String CompanyPostCode2;
String TelephoneNumber2;
String CompanyEMail2;
String CompanyNotes2;
String ClientReference2;
public SqlConnection con;
public void connection()
{
String connectionstr = #"Data Source=ACER\PATTESTSERVER;Initial Catalog=PatTest;Integrated Security=True;Connect Timeout=15;Encrypt=False;TrustServerCertificate=False;";
con = new SqlConnection(connectionstr);
con.Open();
}
private void Finish_Click(object sender, EventArgs e)
{
ClientReference2 = Id.Text;
CompanyName2 = CompanyName.Text;
ClientName2 = ClientName.Text;
CompanyAddress12 = CompanyAddress1.Text;
CompanyAddress22 = CompanyAddress2.Text;
CompanyAddress32 = CompanyAddress3.Text;
CompanyTown2 = CompanyTown.Text;
CompanyPostCode2 = CompanyPostCode.Text;
TelephoneNumber2 = TelephoneNumber.Text;
CompanyEMail2 = CompanyEMail.Text;
CompanyNotes2 = CompanyNotes.Text;
String connectionstr = #"Data Source=ACER\PATTESTSERVER;Initial Catalog=PatTest;Integrated Security=True;Connect Timeout=15;Encrypt=False;TrustServerCertificate=False;";
con = new SqlConnection(connectionstr);
con.Open();
SqlCommand cmd = new SqlCommand("INSERT INTO ClientTable(Id, ClientName, CompanyName, CompanyAddress1, CompanyAddress2, CompanyAddress3, CompanyTown, CompanyPostCode, TelephoneNumber, CompanyEMail, CompanyNotes,) VALUES(#parameter1, #parameter2, #parameter3, #parameter4, #parameter5, #parameter6, #parameter7, #parameter8, #parameter9, #parameter10, #parameter11,)", con);
cmd.Parameters.AddWithValue("#parameter1", ClientReference2);
cmd.Parameters.AddWithValue("#parameter2", ClientName2);
cmd.Parameters.AddWithValue("#parameter3", CompanyName2);
cmd.Parameters.AddWithValue("#parameter4", CompanyAddress12);
cmd.Parameters.AddWithValue("#parameter5", CompanyAddress22);
cmd.Parameters.AddWithValue("#parameter6", CompanyAddress32);
cmd.Parameters.AddWithValue("#parameter7", CompanyTown2);
cmd.Parameters.AddWithValue("#parameter8", CompanyPostCode2);
cmd.Parameters.AddWithValue("#parameter9", TelephoneNumber2);
cmd.Parameters.AddWithValue("#parameter10", CompanyEMail2);
cmd.Parameters.AddWithValue("#parameter11", CompanyNotes2);
cmd.ExecuteNonQuery();
//this method moves to the next screen.
this.Hide();
Asset M1 = new Asset();
M1.Show();
}
private void SaveandNext_Click(object sender, EventArgs e){
ClientReference2 = Id.Text;
CompanyName2 = CompanyName.Text;
ClientName2 = ClientName.Text;
CompanyAddress12 = CompanyAddress1.Text;
CompanyAddress22 = CompanyAddress2.Text;
CompanyAddress32 = CompanyAddress3.Text;
CompanyTown2 = CompanyTown.Text;
CompanyPostCode2 = CompanyPostCode.Text;
TelephoneNumber2 = TelephoneNumber.Text;
CompanyEMail2 = CompanyEMail.Text;
CompanyNotes2 = CompanyNotes.Text;
String connectionstr = #"Data Source=ACER\PATTESTSERVER;Initial Catalog=PatTest;Integrated Security=True;Connect Timeout=15;Encrypt=False;TrustServerCertificate=False;";
con = new SqlConnection(connectionstr);
con.Open();
SqlCommand cmd = new SqlCommand("INSERT INTO ClientTable(Id, ClientName, CompanyName, CompanyAddress1, CompanyAddress2, CompanyAddress3, CompanyTown, CompanyPostCode, TelephoneNumber, CompanyEMail, CompanyNotes,) VALUES(#parameter1, #parameter2, #parameter3, #parameter4, #parameter5, #parameter6, #parameter7, #parameter8, #parameter9, #parameter10, #parameter11,)", con);
cmd.Parameters.AddWithValue("#parameter1", ClientReference2);
cmd.Parameters.AddWithValue("#parameter2", ClientName2);
cmd.Parameters.AddWithValue("#parameter3", CompanyName2);
cmd.Parameters.AddWithValue("#parameter4", CompanyAddress12);
cmd.Parameters.AddWithValue("#parameter5", CompanyAddress22);
cmd.Parameters.AddWithValue("#parameter6", CompanyAddress32);
cmd.Parameters.AddWithValue("#parameter7", CompanyTown2);
cmd.Parameters.AddWithValue("#parameter8", CompanyPostCode2);
cmd.Parameters.AddWithValue("#parameter9", TelephoneNumber2);
cmd.Parameters.AddWithValue("#parameter10", CompanyEMail2);
cmd.Parameters.AddWithValue("#parameter11", CompanyNotes2);
cmd.ExecuteNonQuery();
this.Hide();
AddingClients M1 = new AddingClients();
M1.Show();//Saves the current data then goes to the next record to be tested.

You have an extra comma before the closing ) in your column list and VALUES sections:
SqlCommand cmd = new SqlCommand("INSERT INTO ClientTable(Id, ClientName, CompanyName, CompanyAddress1, CompanyAddress2, CompanyAddress3, CompanyTown, CompanyPostCode, TelephoneNumber, CompanyEMail,
CompanyNotes,)
****
VALUES(#parameter1, #parameter2, #parameter3, #parameter4, #parameter5, #parameter6, #parameter7, #parameter8, #parameter9, #parameter10,
#parameter11,)", con);
****
Remove that and you should be fine

Related

Perform SUM query in ADO.NET

I am getting following error
;expected
I am trying to find sum of column values in my webform.
protected void Page_Load(object sender, EventArgs e)
{
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "Select SUM("AMOUNT DEPOSITED ") From MAIN_TABLE6";
Double amount = cmd.ExecuteScalar();
Label3.Text = amount.ToString();
}
Use brackets to enclose your columns in SQL Server.
protected void Page_Load(object sender, EventArgs e)
{
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "Select SUM([AMOUNT DEPOSITED]) From MAIN_TABLE6";
Double amount = cmd.ExecuteScalar();
Label3.Text = amount.ToString();
}
I update-voted the answer by #ϻᴇᴛᴀʟ because he solved the problem with the brackets. However I like to see that database objects are closed and disposed. If database objects are kept local to the methods where they are used then using blocks accomplish this even if there is and error.
It is possible to pass the connection string directly to the constructor of the connection and pass the command text and connection to the constructor of the command. CommandType.Text is the default value so it is not necessary to set it.
I have opened the connection directly before the .Execute... and it is closed immediately after. The user interface is not updated until the connection is closed.
protected void Page_Load(object sender, EventArgs e)
{
double amount;
using (SqlConnection con = new SqlConnection("Your connection string"))
using (SqlCommand cmd = new SqlCommand("Select SUM([AMOUNT DEPOSITED]) From MAIN_TABLE6;", con))
{
con.Open();
amount = (double)cmd.ExecuteScalar();
}
Label3.Text = amount.ToString();
}

How to save XML data in SQL Server?

In my table there is one XML column. I want to fetch the XML data in one textbox and make some corrections and update it:
private void button2_Click(object sender, EventArgs e)
{
con.Open();
string str = "select C1 from TableName where C2='" + txt1.Text+ "'";
SqlCommand cmd1 = new SqlCommand(str, con);
XmlReader xml = cmd1.ExecuteXmlReader();
xml.Read();
txt2.Text = xml.ReadOuterXml();
XmlDocument doc = new XmlDocument();
doc.PreserveWhitespace = true;
doc.LoadXml(txt2.Text);
}
Now I want to make some changes and update it in my database. When I try to change in textbox it does not work. How can I make changes and update in database? Please help
Update Like this
using (SqlConnection connection = new SqlConnection(connectionString))
using (SqlCommand command = connection.CreateCommand())
{
command.CommandText = "Update TableName set C1 = #C1 where C2 = #C2 ";
command.Parameters.AddWithValue("#C1", Textbox2.Text);
command.Parameters.AddWithValue("#C2", Textbox1.text);
connection.Open();
command.ExecuteNonQuery();
connection.Close();
}

Read XML from SQL Server using OleDbDataReader

I'm stuck trying to read XML data from SQL Server using OleDb.
private static void Main(string[] args){
var con = new OleDbConnection("Provider=SQLNCLI11.1;Data Source=localhost;Integrated Security=SSPI;Initial Catalog=Temp");
var cmd = new OleDbCommand(
"SELECT [Id] ,[Description] FROM [Temp].[dbo].[SomeTable] where [Id]= 1 for xml path, root('root')", con);
con.Open();
byte[] result = null;
OleDbDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
while (reader.Read()){
result = (byte[]) reader[0];
}
MemoryStream stream = new MemoryStream(result);
stream.Position = 0;
XmlDocument doc = new XmlDocument();
doc.Load(stream);
Console.Out.WriteLine(doc.OuterXml);
}
It fails saying that data is malformed. If I convert the byte array to string I see a lot of "strange " characters. What I'm doing wrong?
Since the result is direct XML I believe you are facing issue.You need to get the result in row-set instead of scalar.
Read as String, Use LoadXML instead of stream.
Below is the code I changed.
private static void Main(string[] args)
{
var con = new OleDbConnection("Provider=SQLNCLI11.1;Data Source=localhost;Integrated Security=SSPI;Initial Catalog=Temp");
var cmd = new OleDbCommand(
"Select (SELECT [Id] ,[Description] FROM [Temp].[dbo].[SomeTable] where [Id]= 1 for xml path, root('root')) AS XML", con);
con.Open();
string result = string.Empty;
OleDbDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
if (reader.Read())
{
result = reader[0].ToString();
}
con.Close();
XmlDocument doc = new XmlDocument();
doc.LoadXml(result);
Console.Out.WriteLine(doc.OuterXml);
}

Hitting "COM object that has been separated from its underlying RCW cannot be used" error

I am trying to write a Windows Form program on top of .NET 4.0 and accessing Microsoft Access Database. I can read and write with no problem but sometimes, I get this error:
COM object that has been separated from its underlying RCW cannot be used.
I tried to call this method (GetIDBasedonTeamName) with different inputs twice (on the same thread). The second time this is run, I got that error.
OleDbConnection conn = new OleDbConnection();
OleDbConnection mDB = new OleDbConnection();
OleDbCommand comm = new OleDbCommand();
OleDbCommand cmd;
OleDbDataReader dr;
public void OpenConnection(string name) // always call this method first in other methods to initialise connection
{
conn.ConnectionString = "Provider = Microsoft.Jet.OLEDB.4.0;Data source="
+ Application.StartupPath + "\\AppData\\" + name + ".mdb;";
conn.Open();
comm.Connection = conn;
comm.Parameters.Clear();
}
public string GetIDBasedonTeamName(string teamName)
{
string toReturn = "";
try
{
OpenConnection("form");
comm.CommandText = "Select ID from TeamDetails WHERE TeamName=#teamName";
comm.Parameters.AddWithValue("TeamName", teamName);
dr = comm.ExecuteReader();
while (dr.Read())
{
toReturn = dr[0].ToString();
}
}
catch (OleDbException e)
{
string err = e.Message.ToString();
return null;
}
finally
{
}
conn.Close();
dr.Close();
return toReturn;
}
Exception happened on dr = comm.ExecuteReader();.
The method that was calling this method have this 2 lines inside:
InfoConfig.team1id = Convert.ToInt32(dbm.GetIDBasedonTeamName(cbxTeam1.Text));
InfoConfig.team2id = Convert.ToInt32(dbm.GetIDBasedonTeamName(cbxTeam2.Text));
What could be the cause? I read around and they mentioned not to use different threads but it is the same thread here.
Thanks,
Guo Hong
Building on Martin Liversage's answer:
public string GetIDBasedonTeamName(string teamName) {
var connString = "Provider = Microsoft.Jet.OLEDB.4.0;Data source="
+ Application.StartupPath + "\\AppData\\" + name + ".mdb;";
using (var conn = new OleDbConnection(connString)) {
conn.Open();
using (var cmd = conn.CreateCommand()) {
cmd.CommandText="Select ID from TeamDetails WHERE TeamName = #teamName";
cmd.Parameters.AddWithValue("TeamName", teamName);
using (var rdr = cmd.ExecuteReader()) {
if (rdr.Read()) {
return (string)rdr["TeamName"];
}
//if no valid results will return null
}
}
}
}
Instead of creating the objects only once and storing them in fields in your class you should create, use and close the objects in your method. It is probably the Close you call in the end the method that releases the underlying COM objects giving you the exception on the second call.

Change DataBase using DataGrid

I want to output data from DataBase to DataGrid, using ADO.NET.
Can you tell me how to do that?
When I'm writing something in dataGrid it's changing in database. I use WPF, .NET 4.0.
Code:
class ThemeEditor
{
private SqlDataAdapter da;
private DataSet ds;
private SqlConnection cn;
public ThemeEditor(DataGrid dg)
{
SqlCommand cmd;
string source = "server=(local); integrated security=SSPI; database=tests";
string reqest = "SELECT Theme,Stuff FROM Themes";
cn = new SqlConnection(source);
da = new SqlDataAdapter();
ds = new DataSet();
cmd = new SqlCommand(reqest, cn);
da.SelectCommand = cmd;
da.Fill(ds, "Theme");
dg.ItemsSource = ds.Tables["Theme"].DefaultView;
}
}
maybe it'll be helpfull!
http://support.microsoft.com/kb/307587
or this... http://social.msdn.microsoft.com/Forums/en-US/csharpgeneral/thread/3adacd01-f08f-4059-bbce-bff736a5188e

Resources