I'm newbie in C#
I have 2 methods
In the first method, I want to get the result of the execution sql query - this number (for example 123456) and insert the number (123456) into the text field (second method)
but I do not get the result of running sql query
I use System.Data.SqlClient;
Correct my code please.
//Method for retrieving data from a sql query
private void Form_Load(object sender, EventArgs e)
{
string Qry;
Qry = "select number from TableTest ";
try
{
using (SqlConnection sqlConn = new SqlConnection("Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=Database1.mdf;Integrated Security=True"))
using (SqlCommand cmd = new SqlCommand(Qry, sqlConn))
{
sqlConn.Open();
cmd.CommandTimeout = 300;
SqlDataReader reader = cmd.ExecuteReader();
GetNumber(reader.GetString(2));
}
Application.Exit();
}
catch (Exception ex)
{
MessageBox.Show("Error.Form_Clicker_1_Load" + ex.Message);
}
}
You have to call Read() method. Try like:
..
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
GetNumber(reader[2].ToString());
}
..
Related
Query with parameters works perfectly in ms access database. But when I supply the same parameters from C# winforms application it returns no records.
If the parameter is passed to the query then it will use that parameter in where clause, otherwise it will retrieve all records.
bus table sample data:
Ms-Access Query:
PARAMETERS parPlateNo Text ( 255 );
SELECT bus.*
FROM bus
WHERE (((bus.plateNo) Like IIf(IsNull([parPlateNo]), True ,"%" & [parPlateNo] & "%")));
C# Code:
using (OleDbConnection conn = new OleDbConnection(myGlobals.connString))
{
using (OleDbDataAdapter adapter = new OleDbDataAdapter())
{
using (OleDbCommand cmd = conn.CreateCommand())
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "qryBus";
if(plateNo == "")
cmd.Parameters.AddWithValue("?", DBNull.Value);
else
cmd.Parameters.AddWithValue("?", plateNo);
adapter.SelectCommand = cmd;
dsDetails = new DataSet();
adapter.Fill(dsDetails, "details");
}
}
}
PlateNo is a text column.
Remarks: If I remove the like statement in ms access query and run the same code in C#, it will run perfectly and retrieve all the records in table.
After that, I display the data in datagridview using bindingsource.
Why this is happening?
You using oleDB. You have to change that query and use % as wild cards. DAO, and native Access you use *, but for ADO, or oleDB, you have to use % as the wild cards.
Here are a couple of examples that should help you get this up and running.
private void button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Server=Your_Server_Name;Database=AdventureWorksLT2012;Trusted_Connection=True");
try
{
cmd = new SqlCommand("insert into [dbo].[Student] values(#a,#b,#c)", con);
cmd.Parameters.AddWithValue("#a", int.Parse(textBox1.Text));
cmd.Parameters.AddWithValue("#b", textBox2.Text);
cmd.Parameters.AddWithValue("#c", textBox3.Text);
con.Open();
a = cmd.ExecuteNonQuery();
if (a > 0)
{
MessageBox.Show("Data Submited");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
con.Close();
}
}
AND
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Server=Your_Server_Name;Database=AdventureWorksLT2012;Trusted_Connection=True");
try
{
cmd = new SqlCommand("select * from student where sid=#a", con);
cmd.Parameters.AddWithValue("#a",int.Parse(comboBox1.SelectedItem.ToString()));
con.Open();
dr = cmd.ExecuteReader();
if (dr.HasRows)
{
if (dr.Read())
{
textBox1.Text = dr["sid"].ToString();
textBox2.Text = dr["fname"].ToString();
textBox3.Text = dr["lname"].ToString();
//label1.Text = dr["cdate"].ToString();
}
}
dr.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
con.Close();
}
}
I want to insert my dropdownlist and my textbox values to my database stored procedure but it doesn't insert and also doesn't give me any error. Any ideas what I am doing wrong?
protected void btnPlaceScores_Click(object sender, EventArgs e)
{
string conn = WebConfigurationManager.ConnectionStrings["dbconn"].ConnectionString;
using (SqlConnection myconnection = new SqlConnection(conn))
{
SqlCommand cmd = new SqlCommand("MatchScores", myconnection);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("HomeTeam", drop1.SelectedItem.Value);
cmd.Parameters.AddWithValue("AwayTeam", drop2.SelectedItem.Value);
cmd.Parameters.AddWithValue("Scores", txtScores.Text);
try
{
myconnection.Open();
cmd.ExecuteNonQuery();
}
catch { }
finally
{
myconnection.Close();
}
}
}
Not sure if you're using Microsoft SQL, normally parameters start with an '#'
cmd.Parameters.AddWithValue("#HomeTeam", drop1.SelectedItem.Value);
cmd.Parameters.AddWithValue("#AwayTeam", drop2.SelectedItem.Value);
cmd.Parameters.AddWithValue("#Scores", txtScores.Text);
I am creating a sql project. I used a SqlDatareader and textbox, but when I run it I got an error
InvalidOperationException
My code is this, thanks for your help.
protected void DropDownList2_SelectedIndexChanged(object sender, EventArgs e)
{
if (DropDownList1.SelectedIndex == 0)
{
string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
con.Open();
SqlCommand cmd = new SqlCommand
("USE [PRODUCTS] SELECT QUALITIES FROM dbo.COMPUTERS WHERE ID = 0", con);
SqlDataReader reader;
reader = cmd.ExecuteReader();
TextBox1.Text = reader["QUALITIES"].ToString();
}
}
}
You are not accounting for the case where your data reader has no rows.
Try this:
while(reader.Read())
{
TextBox1.Text = reader["QUALITIES"].ToString();
}
Also note that the "Qualities" field in your database could potentially be null. You will want to protect against this as well.
You should do a couple of error-checking tasks to better understand what is causing the problem. Use a try/catch to analyze the exception more closely. Also add a Finally block to close the reader. And check if the reader has rows:
reader = cmd.ExecuteReader();
try
{
if (reader.HasRows)
{
reader.Read();
if (!reader.IsDBNull(0))
TextBox1.Text = reader.GetString(0);
}
}
catch (Exception ex)
{
// Do something
}
finally
{
reader.Close();
}
Hey everyone pretty new to SQL Database functions but have been coding in c# for about a year now still not that great at it but I'm getting there!
I'm currently creating a football application and to Edit players and Matches i was wanting to use one drop down combo box to retrieve data from an SQL database which then would populate other text boxes and combo boxes. I've had a go at it myself but don't know where i'm going wrong.
On form load my connection opens i populate my datasets and i execute this method to populate my combobox
private void Navigate()
{
string showPlayers = "SELECT * From Add_Players";
SqlCommand cmdData = new SqlCommand(showPlayers, conn);
SqlDataReader myReader = cmdData.ExecuteReader();
while (myReader.Read())
{
comboEditPlayer.Items.Add(myReader[0]);
}
conn.Close();
}
After which in the combo box selected index changed method i have this code
private void comboEditPlayer_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
conn.Open();
string showPlayers = "SELECT * From Add_Players WHERE Player_ID ='"
+ comboEditPlayer + "' ;";
SqlCommand cmdData = new SqlCommand(showPlayers, conn);
SqlDataReader myReader = cmdData.ExecuteReader();
while (myReader.Read())
{
comboEditPlayerPos.Items.Add(myReader[1]);
txtEditPlayerName.Text = myReader[2].ToString();
txtEditPlayerSecond.Text = myReader[3].ToString();
comboEditPlayerStatus.Items.Add(myReader[4]);
}
conn.Close();
conn.Dispose();
}
catch (Exception comboFail)
{
MessageBox.Show(comboFail.ToString());
}
}
I've been told this code is open and i need to use parameterized queries for preventing hacker attempts which i have started but do not know what Parameter i should be adding to the code i have for this is below
private void comboEditPlayer_SelectedIndexChanged(object sender, EventArgs e)
{
string connectionString =
ZimbFootball.Properties.Settings.Default.Football2ConnectionString;
using (SqlConnection connection = new SqlConnection (connectionString))
{
connection.Open();
using (SqlCommand command = new SqlCommand(
"SELECT * From Add_Players WHERE Player_ID ="
+ comboEditPlayer.SelectedValue + "", connection))
{
command.Parameters.Add(new SqlParameter ("",));
}
}
}
All help is appreciated and please go easy on me :P
You could add a parameter to the collection with the value of your ComboBox, then execute the query and read back the values from the reader
private void comboEditPlayer_SelectedIndexChanged(object sender, EventArgs e)
{
string connectionString =
ZimbFootball.Properties.Settings.Default.Football2ConnectionString;
using (SqlConnection connection = new SqlConnection (connectionString))
using (SqlCommand command = new SqlCommand(
"SELECT * From Add_Players WHERE Player_ID =#id", connection))
{
connection.Open();
command.Parameters.AddWithValue("#id", comboEditPlayer.Text);
using(SqlDataReader myReader = command.ExecuteReader())
{
while (myReader.Read())
{
comboEditPlayerPos.Items.Add(myReader[1]);
txtEditPlayerName.Text = myReader[2].ToString();
txtEditPlayerSecond.Text = myReader[3].ToString();
comboEditPlayerStatus.Items.Add(myReader[4]);
}
}
}
}
I am working on a news based site. And the site has a search bar for the Newstitle and I don't want to let SQL injections happen on it.
What I am doing is to get the text from the textbox and then use a query to fetch the matching results. This is what happens when a user clicks the search button:
protected void button_Click(object sender, EventArgs e)
{
string connectionString = ConfigurationManager.ConnectionStrings["connection"].ConnectionString;
SqlConnection conn = new SqlConnection(connectionString);
try
{
SqlCommand comm = new SqlCommand("SELECT * FROM news
Where newstilte LIKE '%" + searchbox.text + "%'", conn);
conn.Open();
SqlDataReader reader = comm.ExecuteReader();
myRepeater.DataSource = reader;
myRepeater.DataBind();
reader.Close();
}
catch (Exception exception)
{
Response.Write(exception.ToString());
}
finally
{
conn.Close();
}
}
As you can see I then use a repeater to show the results. I am wondering how can I prevent SQL injection in the part where people write in the textbox.
USE PARAMETRIZED QUERIES AS BELOW:
protected void button_Click(object sender, EventArgs e)
{
string connectionString = ConfigurationManager.ConnectionStrings["connection"].ConnectionString;
SqlConnection conn = new SqlConnection(connectionString);
try
{
SqlCommand comm = new SqlCommand("SELECT * FROM news
Where newstilte LIKE '%' + #newstilte + '%'", conn);
cmm.Parameters.AddWithValue("#search",searchbox.text) ;
conn.Open();
SqlDataAdapter reader = comm.ExecuteReader();
myRepeater.DataSource = reader;
myRepeater.DataBind();
reader.Close();
}
catch (Exception exception)
{
Response.Write(exception.ToString());
}
finally
{
conn.Close();
}
}
EDIT:
You can also use following if you have datatype kind of restriction for search.
cmm.Parameters.Add(new SqlParameter("#search", SqlDbType.VarChar));
cmm.Parameters["#search"].Value = searchbox.text;
Have a look at THIS doccument.
Try
SqlCommand comm = new SqlCommand("SELECT * FROM news
Where newstilte LIKE '%' + #newstilte + '%'", conn);
comm.Parameters.AddWithValue("#newstilte",searchbox.text)
Use stored procedures with parameters.
.net SQL library properly
SqlCommand comm = new SqlCommand("StoredProcedureName")
comm.CommandType = CommandType.StoredProcedure
cmd.Parameters.AddWithValue("#Parameter", Value)
The .net library should handle most injections.