I have the following code:
dbConnection cn = new dbConnection();
SqlCommand cmd = new SqlCommand();
protected void dropdown_student_SelectedIndexChanged(object sender, EventArgs e)
{
string StudentGUID = dropdown_student.SelectedValue;
cn.con.Open();
cn.cmd.Connection = cn.con;
cn.cmd.CommandText = "select SUM(Marks) AS 'Total' from Marksheet where StudentGUID = " + StudentGUID + " ";
dr = cn.cmd.ExecuteReader();
if (dr.HasRows)
{
while (dr.Read())
{
textbox_total.Text = dr["Total"].ToString();
}
cn.con.Close();
}
}
I want to show the total marks value in the textbox but it does not work. Can anyone point me in the right direction?
Try something like this:
// define your query upfront - using a PARAMETER!
string query = "SELECT SUM(Marks) FROM dbo.Marksheet WHERE StudentGUID = #StudentID;";
// put the SqlConnection and SqlCommand into using blocks
using (dbConnection cn = new dbConnection())
using (SqlCommand cmd = new SqlCommand(query, cn))
{
// define the parameter value
cmd.Parameters.Add("#StudentID", SqlDbType.UniqueIdentifier).Value = dropdown_student.SelectedValue;
cn.Open();
// use ExecuteScalar if you fetch one row, one column exactly
object result = cmd.ExecuteScalar();
cn.Close();
if(result != null)
{
int value = (int)result;
textbox_total.Text = value.ToString();
}
}
You SQL query is wrong. Try like below:
string query = string.Format("SELECT SUM(Marks) FROM dbo.Marksheet WHERE StudentGUID = '{0}';", StudentID);
Always try to follow this kind of standard practice and you will never fail.
Try putting single Quote around the GUID variable in SQL query.
cn.cmd.CommandText = "select SUM(Marks) AS 'Total' from Marksheet where StudentGUID = '" + StudentGUID + " '";
Related
I get an exception I don't understand:
System.Data.SqlClient.SqlException: 'Incorrect syntax near 'Clienti'.'
This is my code leading up to the error:
string connectionString = #"Data Source=VONWOLFENSPC\MSSQLSERVER01;Initial Catalog=Gestionare_excursii_agentie_turism;Integrated Security=True";
SqlConnection sqlCon = new SqlConnection(connectionString: connectionString);
string selectsql = "Select G.Nume, G.Prenume, G.Telefon, G.NumarInsotitori, " +
"G.ClientID, G.Sex, " +
"(Select E.Nume From Excursii E where E.ExcursieID LIKE G.ExcursieID) AS Excursie" +
"From Clienti G Where G.CNP Like #cnp";
SqlCommand cmd = new SqlCommand(selectsql, sqlCon);
cmd.Parameters.AddWithValue("#cnp", comboBox2.Text);
try
{
sqlCon.Open();
// error happens on the next line
using (SqlDataReader read = cmd.ExecuteReader())
{
while(read.Read())
{
//...
}
}
}
finally
{
sqlCon.Close();
}
How can I fix it?
Instead of concatenating the query, use a multi-line string literal:
string selectsql = #"
Select G.Nume, G.Prenume, G.Telefon, G.NumarInsotitori, G.ClientID, G.Sex,
(
Select E.Nume
From Excursii E
where E.ExcursieID LIKE G.ExcursieID
) AS Excursie
From Clienti G
Where G.CNP Like #cnp
";
Which you can paste directly to/from a SSMS query window for testing.
The issue you have is just spaces, if you tried to recheck the string you'll notice a missing space before FROM.
Also, you need to use using
string selectsql = #"SELECT
G.Nume
, G.Prenume
, G.Telefon
, G.NumarInsotitori
, G.ClientID
, G.Sex
, (SELECT E.Nume FROM Excursii E WHERE E.ExcursieID LIKE G.ExcursieID) AS Excursie
FROM
Clienti G
WHERE
G.CNP LIKE #cnp";
using(SqlConnection sqlCon = new SqlConnection(connectionString))
using(SqlCommand cmd = new SqlCommand(selectsql, sqlCon) )
using(SqlDataReader read = cmd.ExecuteReader())
{
cmd.Parameters.AddWithValue("#cnp", comboBox2.Text);
sqlCon.Open();
while(read.Read())
{
textBox1.Text = (read["Nume"].ToString());
textBox2.Text = (read["Prenume"].ToString());
textBox3.Text = (read["Telefon"].ToString());
textBox4.Text = (read["NumarInsotitori"].ToString());
textBox5.Text = (read["ClientID"].ToString());
comboBox1.Text = (read["Excursie"].ToString());
string sex = (read["Sex"].ToString());
if (sex == "M")
{
checkBox1.Checked = true;
checkBox2.Checked = false;
}
else
{
checkBox2.Checked = true;
checkBox1.Checked = false;
}
}
}
I have created a registration page and linked it to Access database now I'm trying to use the information stored on the Db to use on login page but keep getting this "No value given for one or more required parameters." error.
protected void loginButtn_Click(object sender, EventArgs e)
{
string connect = #"Provider=Microsoft.Jet.OleDb.4.0;Data Source=C:\Users\Wisal\Documents\Visual Studio 2012\WebSites\WebSite3\registration-Db.mdb";
string query = "Select Count(*) From client Where [name] = ? And surname = ? and [password] = ?";
int result = 1;
using (OleDbConnection conn = new OleDbConnection(connect))
{
using (OleDbCommand cmd = new OleDbCommand(query, conn))
{
cmd.Parameters.AddWithValue("", nameloginBox.Text);
cmd.Parameters.AddWithValue(" ", snameloginBox.Text);
cmd.Parameters.AddWithValue(" ", passwrdloginBox.Text);
conn.Open();
Session["User"] = nameloginBox.Text;
result = (int)cmd.ExecuteScalar();
}
}
if (result > 0)
{
Response.Redirect("general.aspx");
}
else
{
Literal1.Text = "Invalid credentials";
}
}
As #Rob commented (beat me to it), you are passing 3 parameters with no name. Your code should look something like this, so Access knows what parameters correspond to what variable.
string query = "Select Count(*) From client Where Username = ? And UserPassword = ?";
int result = 1;
using (OleDbConnection conn = new OleDbConnection(connect))
{
using (OleDbCommand cmd = new OleDbCommand(query, conn))
{
cmd.Parameters.AddWithValue("Username", snameloginBox.Text); //username parameter
cmd.Parameters.AddWithValue("UserPassword", passwrdloginBox.Text); //userpassword parameter
conn.Open();
Session["User"] = nameloginBox.Text;
result = (int)cmd.ExecuteScalar();
}
}
For further information about passing parameters to Access queries, please reed here.
I ran the SQL Query in SQL Server Management Studio and it worked.
I get the following error in my WinForm C# application
The parameterized query '(#word1 text)SELECT distinct [database].[dbo].[tableName].[n' expects the parameter '#word1', which was not supplied.
Here is my code
private void buttonRunQuery_Click(object sender, EventArgs e)
{
if (connection == null)
{
connection = ConnectionStateToSQLServer();
SqlCommand command = new SqlCommand(null, connection);
command = createSQLQuery(command);
GetData(command);
}
else
{
SqlCommand command = new SqlCommand(null, connection);
command = createSQLQuery(command);
GetData(command);
}
}
private SqlCommand createSQLQuery(SqlCommand command)
{
string[] allTheseWords;
if (textBoxAllTheseWords.Text.Length > 0)
{
allTheseWords = textBoxAllTheseWords.Text.Split(' ');
string SQLQuery = "SELECT distinct [database].[dbo].[customerTable].[name], [database].[dbo].[customerTable].[dos], [database].[dbo].[customerTable].[accountID], [database].[dbo].[reportTable].[customerID], [database].[dbo].[reportTable].[accountID], [database].[dbo].[reportTable].[fullreport] FROM [database].[dbo].[reportTable], [database].[dbo].[customerTable] WHERE ";
int i = 1;
foreach (string word in allTheseWords)
{
var name = "#word" + (i++).ToString();
command.Parameters.Add(name, SqlDbType.Text);
//(name, SqlDbType.Text).Value = word;
SQLQuery = SQLQuery + String.Format(" [database].[dbo].[reportTable].[fullreport] LIKE {0} AND ", name);
}
SQLQuery = SQLQuery + " [database].[dbo].[customerTable].[accountID] = [database].[dbo].[reportTable].[accountID]";
command.CommandText = SQLQuery;
}
MessageBox.Show(command.CommandText.ToString());
return command;
}
public DataTable GetData(SqlCommand cmd)
{
//SqlConnection con = new SqlConnection(connString);
//SqlCommand cmd = new SqlCommand(sqlcmdString, cn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
connection.Open();
DataTable dt = new DataTable();
da.Fill(dt);
connection.Close();
return dt;
}
The error is happening on da.Fill(dt)
Any suggestions would be helpful
Thank you
In your example, you have commented out the line where you set the value of the Parameter:
command.Parameters.Add(name, SqlDbType.Text);
//(name, SqlDbType.Text).Value = word;
If you do not set a value for a parameter, it is ignored (and won't exist).
Change to this:
command.Parameters.AddWithValue(name, word);
For clarity, consider this quote:
The value to be added. Use DBNull.Value instead of null, to indicate a null value.
From here: SqlParameterCollection.AddWithValue Method
On var name = "#word" + (i++).ToString(); use just i, increment somewhere else.
I want to assign my variable [vPrenom_id_obtenu] by the value that I get in my MySql DB ...
With the following code, I receive an error message :
does not contain a definition for 'ExecuteScalar' ....
string vFistNam_id_get;
string connDataBaseStr = "server=myserver;user=####;database=myDataBase;port=3306;password=dsdfsdfsdf123;";
string sqlDataBaseSelect = "SELECT column_fistname_id FROM table_identy WHERE column_famillyname='" + vFamillyName + "'";
MySqlConnection connDataBase = new MySqlConnection(connDataBaseStr);
connDataBase.Open();
vFistNam_id_get = (string)connDataBase.ExecuteScalar();
connDataBase.Close();
How can I retrieve the value that is in "column_fistname_id"?
The type of two columns of my table
Le type de deux colonnes de ma table [column_fistname_id] and [column_famillyname] is «text'.
ExecuteScalar is a method to call on an instance of a MySqlCommand not of a MySqlConnection
The right way to go is:
using(MySqlConnection connDataBase = new MySqlConnection(connDataBaseStr))
{
connDataBase.Open();
MySqlCommand cmd = new MySqlCommand(sqlDataBaseSelect, connDataBase);
vFistNam_id_get = (string)cmd.ExecuteScalar();
}
However your code is wrong for another reason.
this sql string
string sqlDataBaseSelect = "SELECT column_fistname_id FROM table_identy " +
"WHERE column_famillyname='" + vFamillyName + "'";
leads the way to SqlInjection
You should rewrite it in this way
string sqlDataBaseSelect = "SELECT column_fistname_id FROM table_identy " +
"WHERE column_famillyname=?family";
and then before calling ExecuteScalar add a Parameter to the command
cmd.Parameters.AddWithValue("?family", vFamillyName);
And as added value you don't have to worry about datatype delimiter (single quote in this case)
You need to use MySqlCommand to use ExecuteScalar. You're also missing the SQL in your source code, i.e. select * from something, or a stored proc name.
public static int GetNumRows(String OrchardName)
{
// Create Connection
MySqlConnection con = new MySqlConnection(_connectionString);
// Create Command
MySqlCommand cmd = new MySqlCommand();
cmd.Connection = con;
cmd.CommandText = "SELECT COUNT(*) FROM orchards WHERE OrchardName = #OrchardName";
cmd.Parameters.Add("#OrchardName", OrchardName);
// Return Count
con.Open();
Int32 NumRows = (Int32)cmd.ExecuteScalar();
return NumRows;
}
Example:
MySqlConnection connDataBase = new MySqlConnection(connDataBaseStr);
connDataBase.Open();
MySqlCommand command = connection.CreateCommand();
command.CommandText = "SELECT column_fistname_id FROM table_identy WHERE column_famillyname='" + vFamillyName + "'";
MySqlDataReader reader = command.ExecuteReader();
string vFistNam_id_get = null;
while (reader.Read())
{
vFistNam_id_get = (int)reader["column_fistname_id"];
}
You're using the ADO.NET types wrong. The easiest thing to do would be to use the MySqlHelper static methods, like this:
string vFistNam_id_get = (string)
MySqlHelper.ExecuteScalar(dbConnString, "select `col1` from `table1`");
I need to retrieve Ticket_Id from tbl_Ticket to pass into body section of sending email function..
Is the below code correct?
every times i get Ticket_Id 1..
public int select_TicketId(){
string strConn = System.Configuration.ConfigurationManager.ConnectionStrings["conString"].ConnectionString.ToString();
SqlConnection sqlCon = new SqlConnection(strConn);
string getId = ("select Ticket_Id from tbl_Ticket where Client_EmailAdd='" + objNewTic_BAL.email + "' ");
sqlCon.Open();
SqlCommand cmd1 = new SqlCommand(getId, sqlCon);
int i=cmd1.ExecuteNonQuery();
return i;
}
You are searching for ExecuteScalar which returns the first value.
using System.Configuration;
//
public int select_TicketId()
{
string strConn = ConfigurationManager.ConnectionStrings["conString"].ConnectionString.ToString();
SqlConnection sqlCon = new SqlConnection(strConn);
string getId = ("select TOP 1 Ticket_Id from tbl_Ticket where Client_EmailAdd='" + objNewTic_BAL.email + "' ");
sqlCon.Open();
SqlCommand cmd1 = new SqlCommand(getId, sqlCon);
return Convert.ToInt32(cmd1.ExecuteScalar());
}
Also use CommandProperties to set the where statement for better security, like below:
public int select_TicketId()
{
string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
int result = -1;
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
SqlCommand command = new SqlCommand();
command.Connection = connection;
command.CommandType = CommandType.Text;
command.CommandText = "select TOP 1 Ticket_Id from tbl_Ticket where Client_EmailAdd=#email";
command.Parameters.Add("#email", SqlDbType.Text).Value = objNewTic_BAL.email;
result = Convert.ToInt32(command.ExecuteScalar());
}
return result;
}
You should call int i=(int)cmd1.ExecuteScalar(); method
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executescalar.aspx
You're calling ExecuteNonQuery. But it's a query. This should have rung some warning bells :)
Try ExecuteScalar instead, and cast the result to int...
return (int) cmd1.ExecuteScalar();
Note that you should use using statements for the command and connection as well, so that both are closed appropriately.
And (I hadn't spotted this before) you should definitely use parameterized SQL instead of including a value directly into your SQL. Otherwise you're open to SQL Injection attacks...
So something like:
private const string FetchTicketIdSql =
"select Ticket_Id from tbl_Ticket where Client_EmailAdd = #Email";
public int FetchTicketId()
{
// No need for ToString call...
string connectionString =
ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
using (SqlCommand command = new SqlCommand(connection, FetchTicketIdSql))
{
command.Parameters.Add("#Email", SqlDbType.NVarChar).Value =
bjNewTic_BAL.email;
return (int) command.ExecuteScalar();
}
}
}
You should consider what you want to happen if there isn't exactly one result though...
Hiral,
ExecuteNonQuery in
int i=cmd1.ExecuteNonQuery();
will return number of records that satisfy your query. In this case it is 1 (or 0 if there are no emails)
Try using ExecuteReader instead.