Could somebody tell me why this isn't adding the values to the database. The form runs fine and doesn't return any errors.
private void button1_Click(object sender, EventArgs e)
{
SqlConnection connection = new SqlConnection();
SqlCommand command = new SqlCommand();
connection.ConnectionString = (#"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\John\Documents\Setup.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True");
command.Parameters.AddWithValue("#userName", textBox1.Text);
command.Parameters.AddWithValue("#passWord", textBox2.Text);
command.CommandText = "INSERT INTO Setup (userName, password) VALUES(#userName, #passWord)";
try
{
connection.Open();
int rowsAffected = command.ExecuteNonQuery();
}
catch (Exception ex)
{
// handle exception
}
finally
{
connection.Close();
}
}
FYI: I'm a "newbie" My database is called Setup. I've manually added a table called myTable with 2 columns of userName and another one called password both set at nchar(50)
You need to specify the Table, not the database (which gets used in the connection string). Added the schema prefix to the table name:
command.CommandText = "INSERT INTO dbo.myTable (userName, password) VALUES (#userName, #passWord)";
And add:
command.Connection = connection;
to associate your Command object with the connection object.
Your code should look something like this:
Set the connection object.
Specify the table name as #LarsTech has mentioned.
It is a best practice to use two part notation when specifying table names like [Schema name].[Table Name]. So, you have to specify your table name like dbo.MyTable
Code snippet:
private void button1_Click(object sender, EventArgs e)
{
SqlConnection connection = new SqlConnection();
connection.ConnectionString = (#"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\John\Documents\Setup.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True;");
SqlCommand command = new SqlCommand();
command.Connection = connection;
command.CommandText = "INSERT INTO dbo.MyTable (userName, password) VALUES (#userName, #passWord)";
command.Parameters.AddWithValue("#userName", textBox1.Text);
command.Parameters.AddWithValue("#passWord", textBox2.Text);
try
{
connection.Open();
int rowsAffected = command.ExecuteNonQuery();
}
catch (Exception ex)
{
//handle exception
}
finally
{
connection.Close();
}
}
The form runs fine and doesn't return any errors.
That's probably because you're swallowing them. Get rid of (or log) your catch (Exception ex).
In general, the .NET BCL is well-designed - if a method isn't going to work, you will get an exception.
[Now] I have the error 'ExecuteNonQuery: Connection property has not been initialized.'
Right. You need to pass the SqlConnection to the SqlCommand:
SqlCommand command = new SqlCommand();
command.Connection = connection;
Related
I am trying to store the username and password inside a table called 'User' which is inside a service-based database.
Below is code of what i have tried.
private void Btn_register_Click(object sender, RoutedEventArgs e)
{
try
{
//Create the conection string and open the conn
SqlConnection conne = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=\\CUC-SRV-FS02\Studio-StuHome$\13mihailovs.m\Documents\IT_Unit4\IT_Unit4\ITUnit4.mdf;Integrated Security=True");
//Open the connection string
conne.Open();
//Get all the values from the text boxes etc and pass them over to the DB
string insertQuery = "insert into User(Username, Password) " +
"values(#Username, #Password)";
SqlCommand com = new SqlCommand(insertQuery, conne);
//Get values from the controls such as the text boxes and pass them over to the DB
com.Parameters.AddWithValue("#Username", txt_username.Text);
com.Parameters.AddWithValue("#Password", txt_password.Text);
//This actually executes the query with the given values above.
com.ExecuteNonQuery();
//Dispose the connection string once the data has been passed over the DB
conne.Close();
}
catch (Exception problem)
{
MessageBox.Show("error has occured");
}
}
currect way for insert into database in Ado.Net:
private readonly SqlConnection _con = new SqlConnection("Data Source=.;Initial
Catalog=dbPhoneBook;Integrated Security=True");
public string Add(string user , string pass)
{
string result = "";
SqlCommand cmd = new SqlCommand();
try
{
cmd.Connection = _con;
cmd.CommandText = "insert into tbl_login(user,pass)values(#user,#pass)";
cmd.Parameters.AddWithValue("#user", user);
cmd.Parameters.AddWithValue("#pass", pass);
if (_con.State != ConnectionState.Open)
{
_con.Open();
}
cmd.ExecuteNonQuery();
result = "Ok";
cmd.Dispose();
}
catch
{
cmd.Dispose();
result = "NOk";
}
return result;
}
Also check the following
Check out the web site https://www.connectionstrings.com/ link to the database.
I am trying to write a code that will insert data into a database once user click on button. There's something wrong with the code and it does not seem to work properly. I connect to an external database based on my hosting provider.
private void druk_Click(object sender, EventArgs e)
{
MySql.Data.MySqlClient.MySqlConnection conn;
string myConnectionString;
myConnectionString = "server=s59.hekko.net.pl;uid=truex2_kuba;" +
"pwd=test;database=truex2_kuba;";
try
{
conn = new MySql.Data.MySqlClient.MySqlConnection(myConnectionString);
conn.Open();
MySqlCommand cmd = new MySqlCommand();
}
catch (MySql.Data.MySqlClient.MySqlException ex)
{
MessageBox.Show(ex.Message);
}
cmd.CommandText = "insert into [barcode]values(#class, #tree, #type, #amount, #length, #width, #square)";
cmd.Parameters.AddWithValue("#class", klasa.Text);
cmd.Parameters.AddWithValue("#tree", gatunek.Text);
cmd.Parameters.AddWithValue("#type", rodzaj.Text);
cmd.Parameters.AddWithValue("#amount", amount.Text);
cmd.Parameters.AddWithValue("#length", length.Text);
cmd.Parameters.AddWithValue("#width", width.Text);
cmd.Parameters.AddWithValue("#square", textBox1.Text);
int a = cmd.ExecuteNonQuery();
if (a > 0)
{
MessageBox.Show("Zapisane do raportu");
}
The issue is this:
MySqlCommand cmd = new MySqlCommand();
is in the scope of the try, catch block.
Further on in the code, there was a reference to the cmd variable which is null and hence no data goes in.
Move it outside of the try, catch block.
I have a very basic and beginner problem. I got a 5 line code and I got exception in that.
My database :
It has one table and two columns inside the table viz. id and name.
I made a form.
Here is my code:
private void button1_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection("Data Source=(LocalDB)\\v11.0;AttachDbFilename=\"C:\\Users\\Nicki\\documents\\visual studio 2012\\Projects\\WindowsFormsApplication2\\WindowsFormsApplication2\\Database2.mdf\";Integrated Security=True");
conn.Open();
SqlCommand command = new SqlCommand("INSERT INTO Table (id,name) VALUES (1,'" + textBox1.Text + "')", conn);
command.ExecuteNonQuery();
conn.Close();
}
I get the following exception on running the code:
It says that I have syntax error even though the syntax error is correct. Any help would be appreciated.
Thankyou!
You should use a using clause to properly manage resources and use parameters to avoid security problems. It is not recommended to use reserved words as "table". Try this:
const string commandText = "INSERT INTO [Table] (id,name) VALUES (1,#Name)";
using (SqlConnection connection = new SqlConnection(ConnectionString))
{
SqlCommand command = new SqlCommand(commandText, connection);
command.Parameters.Add("#Name", SqlDbType.VarChar);
command.Parameters["#Name"].Value = textBox1.Text;
connection.Open();
var rowsAffected = command.ExecuteNonQuery();
}
i have been trying to insert data to my database with ASP.net
the code with which i have been trying to insert data:
protected void btnInsert_Click(object sender, EventArgs e)
{
// connection
SqlConnection connection = new SqlConnection();
connection.ConnectionString = #"Data Source=YANNICK\SQLEXPRESS; Initial Catalog=Klas; Integrated Security=True";
SqlCommand command = new SqlCommand();
command.Connection = connection;
// values de insert statement toewijzen
command.Parameters.AddWithValue("#kijkerv", txtGastV.Text);
command.Parameters.AddWithValue("#kijkerT_V", txtGastT_V.Text);
command.Parameters.AddWithValue("#KijkerA", txtGastA.Text);
command.Parameters.AddWithValue("#KijkerEmail", txtEmail.Text);
command.Parameters.AddWithValue("#Kijkershow", txtShowId.integer;
// insert statement
command.CommandText = "INSERT INTO tblKijker (Kijkerv, KijkerT_V, KijkerA, ShowId, Email) VALUES (#kijkerv,
#kijkerT_V, #KijerA, #KijkerEmail, #Kijkershow);";
try {
connection.open();
int rowsAffected = command.ExecuteNonQuery();
} catch (Exception ex) {
// handle exception
} finally {
connection.close();
}
}
the error message is: newline in constant
what does this error mean/ how to fix it?
Your query string CommandText is in two lines. Remove the newline or put # before your query string like this :
command.CommandText = #"INSERT INTO tblKijker (Kijkerv, KijkerT_V, KijkerA, ShowId, Email) VALUES (#kijkerv,
#kijkerT_V, #KijerA, #KijkerEmail, #Kijkershow);"
i have found my own problem:
i had forgotten to add the libraries to set up a connction to my sql into my file
the code would look like this:
// library to work in DATABASES
using System.Data;
// library especially for SQL
using System.Data.SqlClient;
i'm trying to use an insert method in my studentHelperClass, I am trying to activate it on a button click on my form, I don't know how to make it work with a text box, so if someone could help with that, that would be great.
This is my method:
public static void insertStudent()
{
MySqlConnection conn = connection();
conn.Open();
MySqlCommand cmd = new MySqlCommand();
cmd.Connection = conn;
string myInsertSQL = "INSERT INTO person(personID) ";
cmd.Prepare();
myInsertSQL += "VALUES (#personID)";
cmd.Parameters.AddWithValue("#personID", "123345667788");
prevID(conn, cmd);
}
and this is my form:
private void btnInsert_Click(object sender, EventArgs e)
{
studentHelperClass.insertStudent();
}
EDIT:
private static void prevID(MySqlConnection conn, MySqlCommand cmd)
{
conn.Open();
cmd.ExecuteNonQuery();
long studentNumber = (long)cmd.LastInsertedId;
Console.Write("previous id {0} ", studentNumber);
Console.ReadLine();
conn.Close();
}
Considering the information, assuming that your prevId(conn,cmd) is calling ExecuteNonQuery, you will still need to set the cmd.CommandText to be equal to your myInsertSql (as other answers have pointed out).
To answer your question though,
private void btnInsert_Click(object sender, EventArgs e)
{
studentHelperClass.insertStudent(studentIdTextBox.Text);
}
public static void insertStudent(string studentId)
{
MySqlConnection conn = connection();
conn.Open();
MySqlCommand cmd = new MySqlCommand();
cmd.Connection = conn;
string myInsertSQL = "INSERT INTO person(personID) ";
cmd.Prepare();
myInsertSQL += "VALUES (?personID)";
cmd.CommandText = myInsertSQL;
cmd.Parameters.AddWithValue("?personID", studentId);
prevID(conn, cmd);
}
Ive also assumed your studentId is a string. If the database has it as a bigint, you will have to do the proper long.TryParse() call.
You need to set cmd.CommandText as myInsertSQL
and also need to call cmd.ExecuteNonQuery()
string sql = "INSERT INTO person (personID) VALUES (#personID)";
using (MySqlConnection conn = connection())
using (MySqlCommand cmd = new SqlCommand(sql, conn))
{
cmd.Parameters.AddWithValue("#personID", personID);
conn.Open();
cmd.ExecuteNonQuery();
}
You must assign your string variable, 'myInsertSQL' to cmd.CommandText, and then call, cmd.ExecuteNonQuery();
I.e.
cmd.CommandText = myInsertSQL;
cmd.ExecuteNonQuery();
cmd.Dispose();
Always call 'Dispose();' when finished so the .net Garbage Collection can cleanup and manage resources.
You don't use the myInsertSQL string at all, you just set it. You have to set the string as the command text by cmd.CommandText = myInsertSQL and you have to call the method cmd.ExecuteNonQuery().