OleDbCommand is not persisted in the DB - c#

I'm learning C# for a small project with an Access DB.
I get no error when I click on the button to run my sql statement through OleDbCommand but no row is inserted in the table though.
I think my connection is perfectly set up because I get an error if I don't use the right type for a column (e.g. insert a string in an int).
I know the button is working too because I add an action on a text which is working. Finally I know also that my query works since I have tried it directly via VS on my table.
Am I missing a step?
Here my code:
namespace ProjetFalk
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
private void btn_onclick_Click_1(object sender, EventArgs e)
{
label12.Text = string.Empty;
string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;data source=DBFalk.accdb";
OleDbConnection dbconn = new OleDbConnection(connectionString);
dbconn.Open();
string dbcommand = "INSERT INTO Produit (NOM,REFERENCE) VALUES('TEST2', 'test2')"; // + TextBox_Nom.Text + "')";
OleDbCommand cmd = new OleDbCommand(dbcommand, dbconn);
cmd.ExecuteNonQuery();
dbconn.Close();
}
}
}
Please be tolerant, it's new for me. (I have read the docs on Microsoft too for my setup)

Related

Cannot insert item from dropdown menu into my database

I am new to C# and i am trying to insert some values to my database i created inside visual studio.
-I am creating a recipe application-
So in the form i have some components such as text boxes(For title,ingredients,description), a dropdown item(combobox) to specify if it's food or sweet and a button to insert all these data into my database.
When i am pressing the button i can add everything(all the text boxes) to the database except the dropdown value.
Here is the code inside the button_click
private void addItemButton_Click(object sender, EventArgs e)
{
string dat = "Insert into [Table](Title,Category,Ingredients,Description) Values('" + titleTextBox.Text + "','" + dropdownCategory.SelectedValue + "','" + addIngredientTextBox.Text + "','" + addDescriptionTextBox.Text + "')";
SqlConnection sqlCon = new SqlConnection(connectionString);
SqlCommand sqlCmd = new SqlCommand(dat, sqlCon);
sqlCon.Open();
sqlCmd.ExecuteNonQuery();
sqlCon.Close();
}
I make a code example, which can insert the combobox value to the database successfully.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string dat = string.Format("Insert into [Sample](Title,Category,Ingredients,Description)values('{0}','{1}','{2}','{3}')", textBox1.Text, comboBox1.SelectedItem,textBox2.Text,textBox3.Text);
string connectionString = #"connectionstring";
SqlConnection sqlCon = new SqlConnection(connectionString);
SqlCommand sqlCmd = new SqlCommand(dat, sqlCon);
sqlCon.Open();
sqlCmd.ExecuteNonQuery();
sqlCon.Close();
MessageBox.Show("success");
}
private void Form1_Load(object sender, EventArgs e)
{
comboBox1.Items.AddRange(new object[] { "basketball","football", "volleyball" });
}
}
I would try to look into content of string dat.
It might contain invalid data if "dropdownCategory.SelectedValue" returns something
that you don't expect.
Other than that, order of Open(), ExecuteNonQuery() and Close() methods might be incorrect. Try to read docs of these methods.
Another thing that you should look into is error message that is returned(if there is one). They are usually pretty informative.
Ok i don't know if it's correct or not but it worked on me.
I changed
dropdownCategory.SelectedValue
to
dropdownCategory.Text
and it worked.

C# MySQL. Ubable to execute query

private void button4_Click(object sender, EventArgs e)
{
MySqlConnection connection = new MySqlConnection("datasource=localhost;port=3306;Initial Catalog='liblib';Data Source=localhost;username=root;password=admin");
String query = "UPDATE loans SET dataRet=#data1 WHERE loans.idloans = #idloan";
MySqlCommand cmd = new MySqlCommand(query, connection);
int id = Int32.Parse(textBox9.Text);
cmd.Parameters.Add("#data1", MySqlDbType.Date).Value = dateTimePicker1.Value;
cmd.Parameters.Add("#idloan", MySqlDbType.Int32).Value = id;
connection.Open();
if (cmd.ExecuteNonQuery() == 1)
{
MessageBox.Show("Succesful!");
connection.Close();
FIllCard();
}
else
{
MessageBox.Show("Error");
connection.Close();
}
When I execute this UPDATE query in phpmyadmin it works and updates the entry:
UPDATE loans SET dataRet='2017-5-6' WHERE loans.idloans = 23.
But the problem is when I try it in my Form whith parameters. It always returns me "Error" message(ExecuteNonQuery is different from 1), and when I check the database there is no update. The type of the variables in my database are:
idloans - int; dataRet = date;
Check out this post: update a mySQL table using C#, It does not have an answer marked as solution, but the OP of that question has authentication problems after using the code of the first answer, perhaps it works for you

Setting values from ACCESS database as labels in C#

I want to add data from my Access database to a label. the data was searched using a query on FORM1.
OleDbConnection connection = new OleDbConnection();
connection.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Ty\Documents\Uni\Level6\Project\App\software\Databases\Boards.accdb;Persist Security Info=False;";
connection.Open();
OleDbCommand commandBoards = new OleDbCommand();
commandBoards.Connection = connection;
string queryBoardsLength = "select * from [Boards] where [Length] >=" + TxtLength.Text;
string queryBoardsWidth = "select * from [Boards] where [Width] >=" + TxtWidth.Text;
commandBoards.CommandText = queryBoardsLength;
commandBoards.CommandText = queryBoardsWidth;
OleDbDataReader readerBoards = commandBoards.ExecuteReader();
while (readerBoards.Read())
{
ComBoards.Items.Add(readerBoards["ID"].ToString());
}
this populated a combo box on FORM1 with the search results. I then set the selected result from the combo box as a variable when it is selected.
private void ComBoards_SelectedIndexChanged(object sender, EventArgs e)
{
Boards = this.ComBoards.GetItemText(this.ComBoards.SelectedItem);
}
On FORM2 I ran a similar query to gather the exact data from the Access database based on the selected ID. I want to display the length as a label.
private void Form2_Load(object sender, EventArgs e)
{
lblBoardname.Text = Form1.Boards;
OleDbConnection connectionBoards = new OleDbConnection();
connectionBoards.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Ty\Documents\Uni\Level6\Project\App\software\Databases\Boards.accdb;Persist Security Info=False;";
connectionBoards.Open();
OleDbCommand commandBoardsget = new OleDbCommand();
commandBoardsget.Connection = connectionBoards;
string queryBoardsget = "select * from [Boards] where [ID] =" + lblBoardname;
commandBoardsget.CommandText = queryBoardsget;
OleDbDataReader readerBoardsget = commandBoardsget.ExecuteReader();
while (readerBoardsget.Read())
{
lblBoardsizel.Text = readerBoardsget["Length"].ToString();
}
Everything works apart from the Reader on FORM2 where I get the following error:
Syntax error (comma) in query expression '[ID]=System.Windows.Forms.Label, Text: Rhino Boards'.
I would really appreciate some help. Thanks.

MySql connection in C#

i was making a simple windows application form, to register some people in a database, so i made a connection class there is it:
public void Query_send(string cmd)
{
String config = "server=127.0.0.1;uid=root;database=bdcliente;";
MySqlConnection conn = new MySqlConnection(config);
MySqlCommand comm = new MySqlCommand(cmd, conn);
try
{
conn = new MySql.Data.MySqlClient.MySqlConnection();
conn.ConnectionString = config;
conn.Open();
}
catch
{
MessageBox.Show("Error when connecting to the database!");
}
finally
{
conn.Close();
}
}
and then in the BUTTON to give the informations for the MySql i use this:
private void button1_Click(object sender, EventArgs e)
{
Query instance = new Query();
instance.Query_send("INSERT INTO `tbcliente`(`codCliente`, `name`, `cpf`, `telephone`) VALUES ([" + textBox1 + "],[" + textBox2 + "],[" + textBox3 + "],[" + textBox4 + "])");
}
i always get the error with the connection when i click the register button, may someone help me or give me a link of a tutorial that teaches the correct way of doing this?
Thanks, Iago.
My guess is that you need to wrap the VALUES clause results in single quotes as the SQL you are generating will be invalid.
VALUES ('" + textbox1 + "')
Brackets are only required when referring to table or column names. Not when you're referring to string literals.
Odd question, but have you tried applying a password to the database? Depending on the version of MySQL, I have had some issues with leaving the root password unassigned (on local machine you can be safe and just assign 'root' as the password as well). Another option would be to create a user account with permissions and try connection with those credentials.
Not sure if that will help, but it's process of elimination.
Also not sure if method was work in process, but even if it connected there was no execute command against the database.
public void Query_send(string cmd)
{
String config = "server=localhost;uid=root;database=bdcliente;";
MySqlConnection conn = new MySqlConnection(config);
MySqlCommand comm = new MySqlCommand(cmd, conn);
try
{
conn.Open();
comm.ExecuteNonQuery(); '--this was missing
}
catch
{
MessageBox.Show("Error when connecting to the database!");
}
finally
{
conn.Close();
}
}

Null Reference Exception in database handling

in c sharp in win forms i am encountering an error, something like null reference exception
this is my code...and also I don't find any entries in the database table...
public partial class Form1 : Form
{
string strCon, strQry;
SqlConnection con;
SqlCommand cmd;
int rowsaffected;
public Form1()
{
InitializeComponent();
}
box s2 = new box();
class box
{
protected string fname;
protected string lname;
public void name(string s1, string s2)
{
fname = s1;
lname = s2;
}
}
void func(string x, string y)
{
s2.name(x, y);
}
private void btnClick_Click(object sender, EventArgs e)
{
string first = txtFname.Text;
string last = txtLname.Text;
func(first, last);
strQry = "Insert Into Practice Values(" + first + "," + last + " )";
cmd = new SqlCommand(strQry, con);
cmd.Connection.Open();
rowsaffected = cmd.ExecuteNonQuery();
cmd.Connection.Close();
MessageBox.Show(+rowsaffected + " row(s) affected");
}
private void Form1_Load(object sender, EventArgs e)
{
strCon = " Data Source = (local); Initial Catalog = Student; User Id= sa; Password=sa;";
con = new SqlConnection(strCon);
}
alt text http://img682.imageshack.us/img682/6017/hjki.jpg
sorry i didnt mention initialize it u mean to say con = new SqlConnection(strCon); i have done dat in dat case error is {"The name 'xyz' is not permitted in this context. Only constants, expressions, or variables allowed here. Column names are not permitted."}
You are not instantiating the con variable, for example:
SqlConnection con = new SqlConnection(connectionString);
I suppose the error happens because you use con, that is not initialized.
I don't see a SqlConnection con = new SqlConnection(strCon);
I bet your problem is with the connection string, and the connection object is null. Here is a quick way to generate and test a connection string:
Right click the windows desktop or inside a folder in windows explorer,
Click New -> Text Document
Rename the new file to Test.udl (.udl stands for Universal Data Link)
Create and test your connection with the UDL Dialog and click OK
Rename Test.udl to Test.txt and open the text file.
The text file will have a valid connection string that you can use in your code.
Also for your reference, I have simplified your code. The following should be much easier to debug:
private const string dbConnection = "USE THE UDL STRING HERE";
private void btnClick_Click(object sender, EventArgs e)
{
string first = txtFname.Text;
string last = txtLname.Text;
//I think the orig code was missing the single quotes
string query = string.Format("INSERT INTO Practice ('{0}','{1}')", first, last);
int rowsAffected = 0;
//Using statement will automatically close the connection for you
//Using a const for connection string ensures .NET Connection Pooling
using (SqlConnection conn = new SqlConnection(dbConnection))
{
//Creates a command associated with the SqlConnection
SqlCommand cmd = conn.CreateCommand();
//Set your sql statement
cmd.CommandText = query;
//open the connection
cmd.Connection.Open();
//Execute the connection
rowsAffected = cmd.ExecuteNonQuery();
}
MessageBox.Show(rowsAffected + " rows Affected");
}
Are you setting a connection string? It appears you are accessing the Connection object without telling it where to insert the data.
cmd.Connection.ConnectionString = "some string";
I don't think you need cmd.Connection.Open and cmd.Connection.Close.
cmd will open the connection & close it, in order to execute the query/stored procedure.
You are actually creating you connection correctly. What is happening is if you look at your connection string
strCon = " Data Source = (local); Initial Catalog = Student; User Id= sa; Password=sa;";
when it tries to connect it reads this as:
Data Source: " (local)"
Initial Catalog: " Student"
User Id= " sa"
Password - "sa"
So the spaces that you have after the equals signs are getting passed to the SQL server. What your string should look like is this
strCon = "Data Source =(local); Initial Catalog=Student;User Id=sa;Password=sa;"
I am pretty sure that you are never getting an actual connection to your database, but it's failing silently.
Any time you get a null reference on a line that has multiple calls linked together like:
something.somethingElse.somethingElse
break it apart and check each piece. For example, in your case this code:
cmd = new SqlCommand(strQry, con);
SqlConnection sc = cmd.Connection;
System.Diagnostics.Debug.Assert(sc != null, "You got a null connection from the SqlCommand.");
sc.Open();
may demonstrate what the problem is.

Categories

Resources