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();
}
Related
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();
}
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
I have a very slow sql transaction, which inserts new rows in the table. All other "select" queries from another connections wait for this transction to unlock the table.
Is it posible to fetch old rows from the table, while the first transaction works?
SqlExpress 2008 R2.
For exapmle:
private void button1_Click(object sender, EventArgs e)
{
System.Threading.Thread t = new System.Threading.Thread(
delegate()
{
var conn = new SqlConnection(#"Data Source=ARTNB\SQLEXPRESS;Initial Catalog=test;User ID=**;Password=******");
conn.Open();
var cmd = conn.CreateCommand();
var tr = conn.BeginTransaction( IsolationLevel.RepeatableRead, "test");
cmd.Transaction = tr;
cmd.CommandText = #"INSERT INTO Cards (SerialNumber,OperationID,TariffID,RequestTime,State,AgentInfo) VALUES('1213','345',13, GETDATE(),1,'')";
cmd.ExecuteNonQuery();
//very slow transaction
System.Threading.Thread.Sleep(300000);
tr.Commit();
conn.Close();
});
t.Start();
}
private void button2_Click(object sender, EventArgs e)
{
var conn = new SqlConnection(#"Data Source=ARTNB\SQLEXPRESS;Initial Catalog=test;User ID=**;Password=******");
conn.Open();
var cmd = conn.CreateCommand();
var tr = conn.BeginTransaction(IsolationLevel.RepeatableRead, "test2");
cmd.Transaction = tr;
cmd.CommandText = #"SELECT COUNT(*) FROM Cards";
var r = cmd.ExecuteReader();
r.Read();
r.Close();
tr.Commit();
conn.Close();
}
button2_Click method doesnt't fetch a row immidiately, it waits for commit in I have a very slow sql transaction, which inserts new rows in the table. All other "select" queries from another connections wait for this transction to unlock the table.
Is it posible to fetch old rows from the table, while the first transaction works?
SqlExpress 2008 R2.
For exapmle:
private void button1_Click(object sender, EventArgs e)
{
System.Threading.Thread t = new System.Threading.Thread(
delegate()
{
var conn = new SqlConnection(#"Data Source=ARTNB\SQLEXPRESS;Initial Catalog=test;User ID=**;Password=******");
conn.Open();
var cmd = conn.CreateCommand();
var tr = conn.BeginTransaction( IsolationLevel.RepeatableRead, "test");
cmd.Transaction = tr;
cmd.CommandText = #"INSERT INTO Cards (SerialNumber,OperationID,TariffID,RequestTime,State,AgentInfo) VALUES('1213','345',13, GETDATE(),1,'')";
cmd.ExecuteNonQuery();
//very slow transaction
System.Threading.Thread.Sleep(300000);
tr.Commit();
conn.Close();
});
t.Start();
}
private void button2_Click(object sender, EventArgs e)
{
var conn = new SqlConnection(#"Data Source=ARTNB\SQLEXPRESS;Initial Catalog=test;User ID=**;Password=******");
conn.Open();
var cmd = conn.CreateCommand();
var tr = conn.BeginTransaction(IsolationLevel.RepeatableRead, "test2");
cmd.Transaction = tr;
cmd.CommandText = #"SELECT COUNT(*) FROM Cards";
var r = cmd.ExecuteReader();
r.Read();
r.Close();
tr.Commit();
conn.Close();
}
button2_Click method doesnt't fetch a row immidiately, it waits for commit in button1_Click thread.
One quick 'get out of jail' card is enabling read committed snapshot on the database, see Choosing Row Versioning-based Isolation Levels, also mentioned in Deadlocked!. When RCSI is enabled on the database your butonn2 click read will do exactly what you want: it will read an old version of the row, w/o waiting for button1 to commit.
To enable RCSI simply run this once:
ALTER DATABASE [test] SET READ_COMMITTED_SNAPSHOT ON;
Of course there is no free lunch: enabling row-versioning will occur a cost in tempdb IO and size. See Row Versioning Resource Usage. For an Express instance there will be no measurable impact.
I want to delplay the row in the richtextbox
private void button1_Click(object sender, EventArgs e) {
SqlConnection con = new SqlConnection("Data Source=MOSTAFA\\SQLEXPRESS;Initial Catalog=company;Integrated Security=True");
SqlCommand com = new SqlCommand("select * from data where id='"+textBox1.Text+"')",con);
con.Open();
SqlDataReader read = com.ExecuteReader();
if (read.Read())
richTextBox1.Text = "id" + read[0].ToString();
else
label3.Text=("The client didn't found");
}
There's an error in your generated query. You have a closing parenthesis without an opening one. The line as you have it would produce:
select * from data where id='sometest')
which will yield a syntax error from SQL Server.
Try this instead:
SqlCommand com = new SqlCommand("select * from data where id='"+textBox1.Text+"'",con);
You have an extra parenthesis in that SQL statement.
But more importantly, you are leaving yourself wide open for SQL Injection. To get around this devastating and easily avoidable issue is to use parameterized queries.
Is it possible to access the SQL Server "by-product messages" via ADO.NET? Due to the lack of words, by "by-product messages" I mean the output which appears in the Messages tab in Microsoft SQL Server Management Studio. What I particularly have it mind is to read the output of SET STATISTICS TIME ON. It appears that SqlDataReader does not offer anything in this matter.
Yes, there's an event on the SqlConnection class called SqlInfoMessage, which you can hook into:
SqlConnection _con =
new SqlConnection("server=.;database=Northwind;integrated Security=SSPI;");
_con.InfoMessage += new SqlInfoMessageEventHandler(InfoMessageHandler);
The event handler will look like this:
static void InfoMessageHandler(object sender, SqlInfoMessageEventArgs e)
{
string myMsg = e.Message;
}
The e.Message is the message printed out to the message window in SQL Server Management Studio.
Thank you for the response above. I just did a little experiment and found a little unexpected glitch (a bug?) when reading messages (in this case produced by SET STATISTICS TIME ON) from a multi-recordset result. As indicated below, one has to call NextResult even after the last resultset in order to get the last message. This is not needed in the case of a single recordset result.
using System;
using System.Data.SqlClient;
namespace TimingTest
{
class Program
{
static void Main(string[] args)
{
SqlConnection conn = new SqlConnection("some_conn_str");
conn.Open();
conn.InfoMessage += new SqlInfoMessageEventHandler(Message);
SqlCommand cmd = new SqlCommand("some_sp", conn);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read()) { };
rdr.NextResult();
while (rdr.Read()) { };
// this is needed to print the second message
rdr.NextResult();
rdr.Close();
conn.Close();
}
static void Message(object sender, SqlInfoMessageEventArgs e)
{
Console.Out.WriteLine(e.Message);
}
}
}
Based on marc_s' answer, I ve created a wrapper class
public class SqlInfoMessageWrapper
{
public SqlInfoMessageWrapper(SqlConnection connection)
{
SqlConnection = connection;
connection.InfoMessage += new SqlInfoMessageEventHandler(InfoMessageHandler);
}
public SqlConnection SqlConnection { get; set; }
public string Message { get; set; }
void InfoMessageHandler(object sender, SqlInfoMessageEventArgs e)
{
Message = e.Message;
}
}
Example of use :
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
var messageWrapper=new SqlInfoMessageWrapper(connection) ;
var ret = SqlHelper2.ExecuteNonQuery(connection, CommandType.Text, command, null);
messages+= $"{messageWrapper.Message} number of rows affected {ret} ";
}