Hi there guys i am sure this is quite easy i am just completely new to C#.
So I can read the SQL database and bring back results but I cant figure out how to read the returning result which should then be inserted into the Database.
Any idea how I can read the Result View because i can see the value i want in there. Value for this example is 'AS'
SqlConnection con = new SqlConnection("Data Source=###;Initial Catalog=######;Persist Security Info=True;User ID=##;Password=#######");
SqlCommand cmd = new SqlCommand("Select ISOCode from Countries Where CountryName like '" + CTRYLST.SelectedItem + "%'", con);
con.Open();
CTRYLST.Items.Clear();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
CTRYLST.Items.Add(sdr.GetString(0));
}
}
SqlCommand cmd2 = new SqlCommand("INSERT INTO CountryNoMail (ISOCode) VALUES ('" + CTRYLST.Items.ToString() + "');", con);
cmd2.ExecuteNonQuery();
con.Close();
Assuming the sql is correct and everything is fine with the reading, eventually you can inspect the values at runtime by adding a break in the line of additems
You will be able top get back your values by using
CTRYLST.Items[0].ToString;
But it is always preferrable to use a for and cycle since you cannot be sure how many items there will be in the list box. Be careful that items are zerobased, so the first element has 0 as index, the first has 1 and so on.
Related
I have a small table (tbl_user_favs) that is meant to store user favorites. Column 1 is the user ID, and then every column after that is a slot for a selected favorite PC to be stored, denoted Slot1, Slot2.
using (SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\UserFavorites.mdf;Initial Catalog=tbl_user_favs;Integrated Security=True;Connect Timeout=30"))
{
string cmdString = ("SELECT * FROM tbl_user_favs WHERE UserID = '" + Globals.emailUID + "'");
SqlCommand cmd = new SqlCommand(cmdString, con);
cmd.Parameters.Add("#Slot1", SqlDbType.VarChar).Value = PCnum;
DataSet loginCredentials = new DataSet();
SqlDataAdapter dataAdapter;
con.Open();
//dataAdapter = new SqlDataAdapter(cmdString, con);
dataAdapter = new SqlDataAdapter(cmd);
dataAdapter.Fill(loginCredentials);
//cmd.ExecuteNonQuery();
con.Close();
}
Code executes, but it does not add the PCnum to the database next to the UserID. It should lok through the rows, find the UserID that matches the logged in user, Globals.emailUId, and add the PCnum to an open slot. Without worrying yet how to dynamically increment the Slots, why isn't this insert adding the PCnum to Slot 1? I've seen some tutorials use ExecuteNonQuery, and some use the dataAdapter, but both have the same result. I suspect there is something off with my SQL? Thank you
There are a couple things going on here.
First is that you are using "Parameters" incorrectly. It's supposed to add data to your query, not data to the database/row/column after a query has been made.
sql parameterized query in C# with string
Second, you are doing a select query, so you are only getting data from the db, not putting data into it.
To do what you want, you'd need to do this instead: (I don't have a good way to test this, so it may need tweaks, but it should be close.)
using (SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\UserFavorites.mdf;Initial Catalog=tbl_user_favs;Integrated Security=True;Connect Timeout=30"))
{
string cmdString = ("UPDATE tbl_user_favs SET Slot1 = #Slot1 WHERE UserID = #EmailUID");
SqlCommand cmd = new SqlCommand(cmdString, con);
cmd.Parameters.AddWithValue("#Slot1", PCnum);
cmd.Parameters.AddWithValue("#EmailUID", Globals.emailUID);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
You no longer need the DataSet or the SqlDataAdapter.
Since you seem to be confused on what parameterization is and why to use it, check out this question, too.
And here's just some more reading on the topic in general. I used these articles as resources for this answer:
https://visualstudiomagazine.com/articles/2017/07/01/parameterized-queries.aspx
https://www.c-sharpcorner.com/UploadFile/a20beb/why-should-always-use-the-parameterized-query-to-avoid-sql-i/
I'm running a database in SQL2012 and using Visual Studio2012 C# to build a software that interacts with the database, and I've been trying to add a button that interacts with a textbox or something similar that lets the user add/edit rows in the database.
Code:
try
{
string conString = "Data Source=MIRANDA-PC;Initial Catalog=Futebol do Rosa;Integrated Security=True";
SqlConnection con = new SqlConnection(conString);
string selectSql = "Update Players$ SET Player Name='" + textBox3.Text + "' WHERE Player ID= 1";
SqlCommand cmd = new SqlCommand(selectSql, con);
con.Open();
cmd.ExecuteNonQuery();
MessageBox.Show("The values have been UPDATED");
}
catch{
MessageBox.Show("not so fast ***, error found in your ******** code");
}
Ignoring the safety issues (inline SQL is bad. Very bad.) Your update has some fundamental errors. Try:
string selectSql = "Update Players SET Players.Name='" + textBox3.Text +
"' WHERE Players.ID= 1";
Your table columns need to be associated to the table with a . and the table name has to be the same as the one you are updating. I am going on the assumption here that your table name is Players
The code in your link isn't even safe.
Your SqlConnction and SqlCommand will not dispose
The end user can use SQL Injection
Throw your SqlConnection and SqlCommand in an using statement.
using (SqlConnection con = new SqlConnection(constring))
{
using (SqlCommand cmd = new SqlCommand("your query here", con))
{
con.Open();
cmd.ExecuteNonQuery();
}
}
Add parameters to your SqlCommand to avoid SqlInjection
cmd.Parameters.AddWithValue("#param", value);
Create your own class for database interaction and don't put everything in one class or form.
If you let us know what the error is, we can help you more.
Also a good thing is to google your error first.
C# visual studio 2012 professional asp.net
I have a table containing usernames: Josh, Jeremy, Jared, Justin...
And I created a web page gridview that shows the entire table but I only want it to show Justin and nothing else.
How do I do this?
Here's some code that didn't work:
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\Database1.mdf;Integrated Security=True");
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
SqlDataReader rs;
con.Open();
SqlParameter uName = new SqlParameter("paramFName", Account.Text);
cmd.Parameters.Add(uName);
cmd.CommandText = "SELECT * FROM Transactions WHERE FName=#paramFName";
rs = cmd.ExecuteReader();
cmd.Parameters.Clear();
rs.Close();
Am I supposed to create a view of the table? I tried but wasn't successful.
tips?
You simply missed the "#" at the parameter name:
SqlParameter uName = new SqlParameter("#paramFName", Account.Text);
In case of your where-clause this has the effect that you didn't provide anything for the specified parameter which simply let the query provider ignore this condition, which results in the effective query SELECT * FROM Transactions.
Beside you should think about using the using block:
using (SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\Database1.mdf;Integrated Security=True"))
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = con;
cmd.CommandText = "SELECT * FROM Transactions WHERE FName=#paramFName";
cmd.Parameters.AddWithValue("#paramFName", Account.Text);
con.Open();
using (var rs = cmd.ExecuteReader())
{
//ToDo: Do something with the reader.
}
}
And another hint: If you need to fill up a DataTable with the result, you can use a SqlDataAdapter instead of using the data reader:
using (var adapter = new SqlDataAdapter(cmd))
{
var dataTable = new DataTable();
dataTable.TableName = "QueryResult";
adapter.Fill(dataTable);
return dataTable;
}
If you are trying to select the first 10 names for example then you need to change your SQL Select to the following:
cmd.CommandText = "SELECT TOP 10 * FROM Transactions WHERE FName=#paramFName";
Is that what you were after?
EDIT
OK so you are not actually displaying your data anywhere which is the actual problem.
You need to create a datatable and display it in a gridview.
Check out the following links for examples:
Gridview examples
MSDN Gridview examples
Your code seems fine, although you do not provide much information.
If you're using SQL Server 2012 have a look at the keywords OFFSET and FETCH.
For earlier versions you need to use ROW_NUMBER OVER PARTITION
As a good practice you should always limit the number of elements returned.
So im having problem gettin some data in to the database.. Im really stuck, im quite new to c# and have not learned all keywords yet, im not getting any errors just some nothing adds to my database.
textBox2.Text = myPWD;
MySqlConnection conn = new MySqlConnection("test")
string Query = "INSERT INTO `users`.`coffekeys` (`koffekeys`) VALUES ('values = #val')";
MySqlCommand data = new MySqlCommand(Query, conn);
MySqlDataReader myReader;
conn.Open();
SelectCommand.Parameters.AddWithValue("#val", this.textBox2.Text);
conn.Closed()
Manipulate the concatenation of value in passing of parameters. Don't do it inside sql statement.
string Query = "INSERT INTO `users`.`coffekeys` (`koffekeys`) VALUES (#val)";
// other codes
SelectCommand.Parameters.AddWithValue("#val", "values = " + this.textBox2.Text);
the reason why the parameter is not working is because it was surrounded by single quotes. Parameters are identifiers and not string literals.
The next problem is you did not call ExecuteNonQuery() which will execute the command.
Before closing the connection, call ExecuteNonQuery()
// other codes
data.ExecuteNonQuery();
conn.Close();
You should Google around and you will receive lots of content
You need to run ExecuteNonQuery
SqlConnection con = new SqlConnection(constring);
con.Open();
SqlCommand cmd = new SqlCommand(
"insert into st (ID,Name) values ('11','seed');", con);
cmd.ExecuteNonQuery();
cmd.Close();
I basically want to store some values into the database.
I keep getting the error "Number of query values and destination fields are not the same."
pointing towards the dr = cmd.ExecuteReader();
Can someone please help me? :)
I am kinda new to the whole thing and don't really know whats happening.
Bellow is the code am using.
public partial class Registeration_experiment : System.Web.UI.Page
{
static OleDbConnection con = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\New folder\Project 1.0\WebSite1\New Microsoft Office Access 2007 Database.accdb");
OleDbDataAdapter ada = new OleDbDataAdapter();
OleDbCommand cmd = new OleDbCommand();
OleDbDataReader dr;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
string str = "insert into Registeration_Test (Name1, address, emailaddress)" +
"values (?, ?, ?)";
con.Open();
cmd = new OleDbCommand(str, con);
cmd.Parameters.AddWithValue("#p1", TextBox1.Text);
cmd.Parameters.AddWithValue("#p2", TextBox2.Text);
cmd.Parameters.AddWithValue("#p4", TextBox4.Text);
cmd.ExecuteNonQuery();
}
}
Thank you :)
You are writing to the database, not reading from it.
No sense to use ExecuteReader, you need a ExecuteNonQuery for that
EDIT
Seeing now the structure of the table. It is composed of 5 fields.
In this case, you have two choices. Provide the name of the fields that you want to update in the insert statement or add a parameter for every field
First choice, you don't give the name of the fields
(pass a parameter for every field except the ID because I suppose it is an AutoIncrement field, meaning that the database manages itself the value for that field)
// No name provided for fields, need to pass a parameter for each field
string str = "insert into Registeration_Test values (?, ?, ?, ?)";
con.Open();
cmd = new OleDbCommand(str, con);
cmd.Parameters.AddWithValue("#p1", Textbox1.Text);
cmd.Parameters.AddWithValue("#p2", Textbox2.Text);
cmd.Parameters.AddWithValue("#p3", Textbox3.Text);
cmd.Parameters.AddWithValue("#p4", Textbox4.Text);
cmd.ExecuteNonQuery();
(Note, the TextBox1... etc are the names you have provided in you example above, I don't know the exact content of these textboxes where the user types the data to insert in the database, nor I don't know if they really exists in your page/form)
Second choice, you declare the fields that should be updated in the database
// Just three named fields updated
string str = "insert into Registeration_Test (Name1, address, emailaddress)" +
"values (?, ?, ?)";
con.Open();
cmd = new OleDbCommand(str, con);
cmd.Parameters.AddWithValue("#p1", Textbox1.Text);
cmd.Parameters.AddWithValue("#p2", Textbox2.Text);
cmd.Parameters.AddWithValue("#p4", Textbox4.Text);
cmd.ExecuteNonQuery();
Please note also that I have changed your sql command to not use string concatenation.
It is a very bad practice that leads to numerous problem. The worst one is Sql Injection, not to mention problems with string parsing when text contains single quotes or other problematic characters
A parameter placeholder is represented (in OleDb) by the ? in the command text. This placeholder will be replaced by the actual value added in the parameter collection of the OleDbCommand (in the exact order in which the placeholders appears). Using Parameters (Parametrized query) allows the framework to examine the values passed and take appropriate actions if these values are invalid.
EDIT
The problem with connection arises from a previous command that has left the connection open. This is another bad practice. Every connection should be: created, opened, used, closed. The pseudocode to follow is this
// Create the connection
using(OleDbConnection con = GetOleDbConnection())
{
con.Open();
... // use the connection with insert/delete/update/select commands
}
// Exiting from the using block close and destroy (dispose) the connection