What I need to do is basically take the users name (which is already stored as a variable) and their score (which is also a variable) and store it in my database when they press 'submit'. Here is the code I have for the button click.
private void btnSubmitScore_Click(object sender, EventArgs e)
{
string connStr = "server=server; " +
"database=databasename; " +
"uid=username; " +
"pwd=password;";
MySqlConnection myConn = new MySqlConnection(connStr);
}
Obviously i have changed the login details etc. I have had a look around and have only managed to find confusing codes about how to display data from a database in a form (i will do this later), but for now, i need to know how to add sName and iTotalScore into the database. (Fields are called 'Name' and 'Score' in DB)
You are going to use a combination of SqlConnection, SqlCommand and their properties. the connection is essentially the stuff of your code. The command is a literal SQL statement, or a call to a stored procedure.
A common C# idiom is to form your code around the very first line as shown here:
using (SqlConnection myConnection = new SqlConnection()) {
string doThis = "select this, that from someTable where this is not null";
SqlCommand myCommand = new SqlCommand(dothis, myConnection);
try {
myCommand.Connection.Open();
myReader = myCommand.ExecuteReader(); //pretend "myReader" was declared earlier
} catch (Exception myEx) {
// left to your imagination, and googling.
}
finally {
myCommand.Connection.Close();
}
}
// do something with the results. Your's to google and figure out
The general outline is
Using a connection
instantiate and configure an SqlCommand
Use try/catch as shown.
The "using" block gives use behind the scenes cleanup/disposal of all those objects we don't need anymore when we're done; in particular the SqlConnection object.
You must learn more about these Sqlxxxxx classes, there's lots of ways to configure them to do what you want.
I am not familiar with the MySql connector, but the code should be something along the lines of:
private void Insert()
{
string connStr = "server=server; " +
"database=databasename; " +
"uid=username; " +
"pwd=password;";
string query = "INSERT INTO TableName('Name','Score) VALUES (#name, #score);";
using(MySqlConnection connection = new MySqlConnection(connStr))
{
MySqlCommand insertCommand = new MySqlCommand(connection,command);
insertCommand.Paramaters.AddWithValue("#name",sName);
insertCommand.Paramaters.AddWithValue("#score",iTotalScore);
connection.Open();
command.ExecuteNonQuery();
connection.Close();
}
}
Related
I have created a class for the MS Access database connection. It works fine on the majority of the forms within my Winforms app. However, I have a form where the user can add, edit or delete information from the database. I've constructed that part using a string, but when I remove the long database connection string I had there before and replace it with the class I created it throws an exception.
I've tried changing the code by removing the string, but I want to use the string method.
This is the code I have for the delete button click event
string con = (#"Provider = Microsoft.ACE.OLEDB.12.0; Data Source =C:\Users\folder\Desktop\ApplicationFolder\AppName\bin\Debug\DataBase\DatabaseName.accdb");
string Query = "delete from Employees2 where EmployeeName = '" +
this.txtAdminFEmployee.Text + "' ; ";
OleDbConnection ConnectionString = new OleDbConnection(con);
OleDbCommand command = new OleDbCommand(Query, ConnectionString);
OleDbDataReader reader;
try
{
ConnectionString.Open();
reader = command.ExecuteReader();
DialogResult result = MessageBox.Show("Employee Deleted Successfully",
"Information",
MessageBoxButtons.OK, MessageBoxIcon.Information);
while (reader.Read())
{
}
}
catch (Exception ex)
{
MessageBox.Show("Error " + ex);
ConnectionString.Close();
This is the database class I created
using System.Data.OleDb;
namespace AppName
{
class OledbConnect
{
public OleDbConnection con;
public void Connection()
{
con = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\DatabaseName.accdb");
}
}
}
I need to know how to use the database class in that string. I've tried different ways but nothing works. I am still new to c# and Google is not really returning anything I can use. Thanks
Your initial code works, but confusion is evident in the naming of variables.
string con = #"Provider = Microsoft.ACE.OLEDB.12.0; Data Source =C:\Users\folder\Desktop\ApplicationFolder\AppName\bin\Debug\DataBase\DatabaseName.accdb";
(I've taken the un-needed parentheses off the declaration; it's just a string.)
Calling that string 'con' is a bit confusing. I'd call it 'connectionString', or maybe 'cs' for short.
OleDbConnection ConnectionString = new OleDbConnection(con);
OleDbCommand command = new OleDbCommand(Query, ConnectionString);
OK, so you correctly create an OleDbConnection, passing the connection string (con) to its constructor. This is good. But you confusingly call it ConnectionString. It isn't the connection string; it's the connection, and your code thereafter uses it correctly.
So that works. Confusing for a human to read because of the mis-naming of variables, but the compiler doesn't care what their names are - it knows very well that ConectionString is an OleDbConnection and doesn't feel any of the cognitive dissonance that I do when I look at it.
If you rename the variables in the original code as I've suggested, and then copy that code into your class (BTW, I'd just call it DbConnection; it's current name is very close to another class name which might also be confusing), paying attention to what each statement does and what each variable represents then you should be good to go.
I am making a project in C#- in which one can "vote".
When you run the program you first log in. After you've logged in you have to select a value out of a dropdownlist. After you've selected the teacher you press on a button which votes.
The problem is I don't really know how to let this validate properly. And to check if the person has already voted.
It has to check the column in the database named "disabled" if the value = 1 or 0. If the value = 1 they can't vote and if it's 0 they can.
When the person votes it increases the column aantalStemmen by 1. and the disabled column to 1 aswell. Which gets shown in a datagridview.
And the values in the dropdownlist has to match the 1 in the database.
I have this code:
private void db_connection()
{
try
{
conn = "Data Source=localhost;Initial Catalog=docent;Integrated Security=True";
connect = new SqlConnection(conn);
connect.Open();
}
catch (SqlException e)
{
throw;
}
}
private bool validate_disabled(string favoriet)
{
db_connection();
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "Select disabled from leerling";
cmd.Connection = connect;
SqlDataReader disabled = cmd.ExecuteReader();
if (disabled.Read())
{
connect.Close();
return true;
}
else
{
connect.Close();
return false;
}
}
private void btnStem_Click(object sender, EventArgs e)
{
string favoriet = cmbFavoriete.Text;
db_connection();
SqlCommand cmd = new SqlCommand();
bool r = validate_disabled(favoriet);
if(r){
cmd.CommandText = "UPDATE docent SET aantalStemmen = aantalStemmen + 1 where docentid=#id";
cmd.Parameters.AddWithValue("#id", cmbFavoriete.Text);
}
else
{
MessageBox.Show("You have already voted.");
}
}
my tables in my database looks like this:
Thanks in advance, I've been struggling really hard with this as I'm still a rookie in C#.
I will try an answer to cover more aspects of your code (many already mentioned in comments):
1) Declare your connection string outside of your methods. Also choose meaningful variable names - you will than yourself in a few months when you revisit the code.
private const String ConnectionStr = "Data Source=localhost;Initial Catalog=docent;Integrated Security=True";
2. Appropriate names for methods - also, try to use Camel or Pascal case for method names.
3. Pay attention to possible exceptions. SQLException is not the only possible exception when constructing or opening an SqlConnection, so it is better to catch anything that might occur
private SqlConnection createConnection
{
try
{
connect = new SqlConnection(ConnectionStr);
connect.Open();
}
// this is laziness, but it is better than before
catch (Exception e)
{
// best to log the real error somewhere
throw;
}
}
4. Dispose connection and other disposables like SqlCommand. Also var might save some typing (just hover your mouse over the keyword and you will see the actual type).
SqlConnection allows to directly create a command to be executed using that particular connection by using CreateCommand.
Since your are expecting a single value (scalar) (or a single row with a single column), you can use ExecuteScalar method. So, no more reader.
private bool isDisabled(string favoriet)
{
using (var connection = createConnection())
{
using (var cmd = new connection.CreateCommand())
{
cmd.CommandText = "Select disabled from leerling where leerlingnummer = #number";
cmd.Parameters.AddWithValue("#number", favoriet);
// for simplicity I have assumed that it will always find a value. This should be checked
var disabled = Convert.ToBoolean(cmd.ExecuteScalar());
return disabled;
}
}
}
5. Try not to mix UI logic with database logic (they are usually put in different assemblies)
private void castVote(String favoriete)
{
using (var connection = createConnection())
{
using (var cmd = new connection.CreateCommand())
{
cmd.CommandText = "UPDATE docent SET aantalStemmen = aantalStemmen + 1 where docentid = #id";
cmd.Parameters.AddWithValue("#id", cmbFavoriete.Text);
// command must be actually executed, otherwise nothing happens
cmd.ExecuteNonQuery();
}
}
}
private void btnStem_Click(object sender, EventArgs e)
{
string favoriet = cmbFavoriete.Text;
bool r = isDisabled(favoriet);
if (r)
castVote(favoriet);
// maybe, it would make sense to also notify the user that the vote has been cast
else
MessageBox.Show("You have already voted.");
}
6. Use EntityFramework - in order to avoid the troubles related to handling commands and readers, you can use an ORM to do the dirty work for you.
I would suggest you use bit Data Type (0 - false, 1 - true) instead of int Data Type in your table. It does exactly what you need and you don't have to use int for this.
This means you could change your validate_disabled method to use something like this:
cmd.CommandText = "SELECT disabled FROM leerling WHERE disabled = 1 AND leerlingnummer = #favoriet";
cmd.Parameters.AddWithValue("#favoriet", favoriet);
I've assumed string favoriet is equal to leerlingnummer in your table. After you've executed that query, you would simply check if the query contains more than 0 records - if more than 0 records that means the person does not have permission to vote.
I have written this simple code in c# VS 2010 to store the name and login to my local table. When i run it is shows me this massage:
"incorrect syntax near the nvarchar"
using System;
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
string name =textBox1.Text;
string login =textBox2 .Text;
string sqlquery;
SqlConnection cn = new SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename= C:\\Users\\Safeen\\Documents\\Visual Studio 2010\\Projects\\WindowsFormsApplication12\\WindowsFormsApplication12\\Database1.mdf;Integrated Security=True;User Instance=True");
cn.Open();
sqlquery = "INSERT INTO Table1 (user, password) VALUES ('" + name + "','" + login + "')";
try
{
SqlCommand command = new SqlCommand(sqlquery, cn);
command.Parameters.AddWithValue("#user ", textBox1.Text);
command.Parameters.AddWithValue("#password ", textBox2.Text);
command.ExecuteNonQuery();
MessageBox.Show("Table1 Added");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
textBox1.Clear();
textBox2.Clear();
cn.Close();
}
}
You're providing multiple values for your parameters.
You're saying the db value of user = name and password = login, then ALSO passing in two parameters called #user and #password, without telling SQL which set is correct.
You definitely want to go with SqlCommand option and also set the SqlCommand.CommandType to the correct value. Assigning parameters like this is safe; dropping variables directly into the VALUES() clause (like you had in your original post) can open yourself to SQL Injection attacks.
I edited out a recommendation to use Stored Procs here. That's more of a personal preference I have, as per the little discussion in the comments; I like to separate out my database layer. Also, it means that if anything ever changes you just have to update your Stored Proc once instead of finding your query everywhere it could be in your app.
I'm receiving the following error message:
invalidOperationException was unhandled
In the following code:
private void btnInsert_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection("Data Source=DASTGIRKHAN\\SQLEXPRESS;Initial Catalog=DBProject;Integrated Security=True;Pooling=False");
conn.Open();
SqlCommand cmd = new SqlCommand("Insert INTO EmployeeRecord Values(" + tfCode.Text + ",'" + tfName.Text + "','" + tfCell.Text + "','" + tfAdrs + "',)");
cmd.BeginExecuteNonQuery();
cmd.ExecuteNonQuery();
conn.Close();
MessageBox.Show("Inserted Successfully");
}
InvalidOperationException exception is thrown when you invoke BeginExecuteNonQuery method (msdn) and you not specified "Asynchronous Processing=true" in the connection string.
You should also set connection to your command:
SqlCommand cmd = new SqlCommand("Insert INTO EmployeeRecord Values(" + tfCode.Text + ",'" + tfName.Text + "','" + tfCell.Text + "','" + tfAdrs + "')", conn);
InvalidOperationException
The name/value pair "Asynchronous Processing=true" was not included
within the connection string defining the connection for this
SqlCommand. The SqlConnection closed or dropped during a streaming
operation.
Sorry but your code has many errors. Let me show a different approach
private void btnInsert_Click(object sender, EventArgs e)
{
string cnString = #"Data Source=DASTGIRKHAN\\SQLEXPRESS;
Initial Catalog=DBProject;
Integrated Security=True;";
string cmdText = #"Insert INTO EmployeeRecord
Values(#code,#fname,#cell,#adr)";
using(SqlConnection conn = new SqlConnection(cnString))
using(SqlCommand cmd = new SqlCommand(cmdText, conn))
{
conn.Open();
cmd.Parameters.AddWithValue("#code", Convert.ToInt32(tfCode.Text));
cmd.Parameters.AddWithValue("#fname", tfName.Text );
cmd.Parameters.AddWithValue("#cell", tfCell.Text );
cmd.Parameters.AddWithValue("#adr", tfAdrs.Text);
int rowsInserted = cmd.ExecuteNonQuery();
if(rowInserted > 0)
MessageBox.Show("Inserted Successfully");
else
MessageBox.Show("Insert failes");
}
}
The primary cause of your error is stated by the answer of kmatyaszek, but this is just the tip of the iceberg.
You should always use the using statement around your disposable objects like the connection. This will ensure that the connection is closed and disposed also in case of exceptions.
You should use a parameterized query to create your command to avoid Sql Injection and parsing problems. For example, a single quote in the tfName textbox could lead to a Syntax Error.
The call to BeginExecuteNonQuery, excludes the call to ExecuteNonQuery and requires a call to EndExecuteNonQuery.
Finally, the result of ExecuteNonQuery tells you if the insertion is successful.
As a last note, I have remove the Pooling=False from the connection string.
You haven't said anything why do you want avoid his very useful optimization.
I'd print that SQL text. Looks like there's an unbalanced apostrophe to me.
Better yet, use a .NET class that binds parameters for you. Easier and better SQL injection projection, too.
What are tfCode, tfName,tfCell,tfAdrs? I assume they are textbox control?
if so you are using tfAdrs instead of tfAdrs.Text
also assign connection string to the command and remove additional space in
"Integrated security"
Why complicate yourself, use Parameterized Insert instead of concatenation, which its prone to SQL Injection.
SqlCommand command1 = new SqlCommand("INSERT INTO EmployeeRecord VALUES(#tfCode, #tfName, #tfCell, #tfAdrs)", conn);
command1.Parameters.AddWithValue("#tfCode", trCode);
command1.Parameters.AddWithValue("#tfName", tfName);
command1.Parameters.AddWithValue("#tfCell", tfCell);
command1.Parameters.AddWithValue("#tfAdrs", tfAdrs);
I have read TONS of tutorials, articles and whatever regarding my issue and honestly, due to my lack of experience I can't twist my fingers around this one so I hope some of you guys can help me out :)
I am working on a project (simply to learn how to program so it's probably very basic), but I have this "News" page where I can update and delete data using a GridView.
Now I would like to INSERT something into my database using 3 textboxes and 1 submit button.
I have 3 rows that has to be inserted:
Headline
Date
Content/the news itself.
Which are stored under NyhedTB from the connectionstring: BoligStjernenConnectionString
My query looks like this:
INSERT INTO [NyhedTB] ([NyhedDato], [NyhedTitel], [NyhedTekst])
VALUES (#NyhedDato, #NyhedTitel, #NyhedTekst)
I read on the internet that this code should do the magic for me (I will have to insert my own values ofc.):
static void Insert()
{
try
{
string connectionString =
"server=.;" +
"initial catalog=employee;" +
"user id=sa;" +
"password=sa123";
using (SqlConnection conn =
new SqlConnection(connectionString))
{
conn.Open();
using (SqlCommand cmd =
new SqlCommand("INSERT INTO EmployeeDetails VALUES(" +
"#Id, #Name, #Address)", conn))
{
cmd.Parameters.AddWithValue("#Id", 1);
cmd.Parameters.AddWithValue("#Name", "Amal Hashim");
cmd.Parameters.AddWithValue("#Address", "Bangalore");
int rows = cmd.ExecuteNonQuery();
//rows number of record got inserted
}
}
}
catch (SqlException ex)
{
//Log exception
//Display Error message
}
}
I looked at this code and thought it should be easy enough but really, I can't figure it out.
Here is some advice to get you going, learning programming is a lot of
trial and error.
Start off basic, litrally put three textboxes on a form/page and a
button.
Double click the button to go the code-behind and view the buttons
click event.
Paste in the body of code included with your question (everything in the try-catch).
Put a break-point on the Public Void Button_Click line of code and press F11 to
step through the code.
"one thing is having the code-behind working but how to make the buttons and textboxes working is still a misery"*
Put the textbox as the value rather than your hardcoded values:
cmd.Parameters.AddWithValue("#Address", textBox1.Text);
You also should not insert the Id value, instead modify the EmployeeDetails table and set the ID column to in the properties set Identity Specification (IS Identity) = True. Then right click the ID column and set Primary Key.
Post any error messages you encounter here and when you do get get it working, an additional exercise (that will be very valuable for you) would use a database stored procedure rather than ad-hoc SQL, to safe-guard against sql-injection attacks.
I'm assuming you have SQL Server installed and have a 'employee' database with a table called EmployeeDetails.
protected void GvManualShows_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
//label lbl = (label)e.Row.FindControl("lblHidden");
if (e.Row.Cells[14].Text == "Y")
{
// CheckBox cb = (CheckBox)e.Row.FindControl("chk");
CheckBox chk = (CheckBox)e.Row.Cells[0].FindControl("chkBox");
chk.Checked = true;
}
}
}
It's fairly simple. You just have to modify the connection string, the query and its parameters:
private void button1_Click(object sender, EventArgs e)
{
try
{
string connectionString =
"server=SQLServer;" + // SQLServer is your SQL server machine
"initial catalog=employee;" + // employee is your database
"user id=sa;" + // sa is the login to connect the database
"password=sa123"; // sa123 is the password of the login
using (SqlConnection conn =
new SqlConnection(connectionString))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand(
"INSERT INTO [NyhedTB] ([NyhedDato], [NyhedTitel], [NyhedTekst]) " +
"VALUES (#NyhedDato, #NyhedTitel, #NyhedTekst)", conn))
{
cmd.Parameters.AddWithValue("#NyhedDato", textBoxDate.Text);
cmd.Parameters.AddWithValue("#NyhedTitel", textBoxTitle.Text);
cmd.Parameters.AddWithValue("#NyhedTekst", textBoxBody.Text);
int rows = cmd.ExecuteNonQuery(); // Inserted rows number
}
}
}
catch (SqlException ex)
{
//Log exception
//Display Error message
}
}
I made changed example code with your requirements and added comments, hope it would be a bit clearer for you to understand whats going on:
static void Insert()
{
try
{
string connectionString =
"server=.;" +
"initial catalog=MyDatabaseName;" + //here you write database name where your NyhedTB table is
"user id=sa;" + //user name to connect to database
"password=sa123"; //password
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
using (SqlCommand cmd =
new SqlCommand("INSERT INTO NyhedTB (NyhedDato, NyhedTitel, NyhedTekst) VALUES (#NyhedDato, #NyhedTitel, #NyhedTekst)", conn))
{
//all "things" in your sql command what beggins with #
//means that it is parameter and you need to pass values for these parameters:
//For #NyhedDato parameter you set text from your textbox
cmd.Parameters.AddWithValue("#NyhedDato", txtDate.Text);
//For #NyhedTitel parameter you set text from title textbox
cmd.Parameters.AddWithValue("#NyhedTitel", txtTitle.Text);
//For #NyhedTekst parameter you set text from content textbox
cmd.Parameters.AddWithValue("#NyhedTekst", txtContent.Text);
//Execute insert command and get how many records was efected, in this case it should be rows = 1 because you inserting just one record
int rows = cmd.ExecuteNonQuery();
}
}
}
catch (SqlException ex)
{
//Log exception
//Display Error message
}
}
P.s. code not tested. And when you say
I have 3 rows that has to be inserted:
Headline
Date
Content/the news itself.
actually you mean you want to insert record with fields