Error creating table in MySQL database using C# - c#

This error occurs whenever i'm trying to run my program.
Additional information: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ')' at line 1
The code is as follows:
private void create_Click(object sender, EventArgs e)
{
string MyConnectionString = "Server=x.x.x.x;Database=groupdes_New;Uid=root;Pwd=password;";
//create connection
MySqlConnection connection = new MySqlConnection(MyConnectionString);
//connect to database
connection.Open();
MySqlCommand cmd;
cmd = connection.CreateCommand();//create command
cmd.CommandText = "CREATE Table Newtable (" + "name" + ")";
cmd.ExecuteNonQuery();
if (connection.State == ConnectionState.Open)
{
connection.Close();
}
}
I still can't manage to solve this error. Thanks for the help!

Your create table sintaxis is wrong.
You need define field datatype
CREATE TABLE Table1
(`myDate` datetime)
;

Related

c# Language : Error while trying to save parameters to MySql DB using C#

I am using MySql database in my C# program.
Below is my code and when I execute the following method, it throws me an exception "MySql Syntax Exception".
Please help me in figuring out the error. Also let me know, if any further information is required to resolve this.
I would be very glad if you guys can help me.
private void btnVerify_Click(object sender, EventArgs e)
{
con.Open();
try
{
string cmdText = "INSERT INTO cheque(customer_name, national_id, drawn_bank, chq_number, bnk_br_code, ac_number, drawndate, amount, commission_rate, commission, order, recieved_date, due_date, reminder_date, chq_image_frnt, chq_image_back) VALUES(#customer_name,#national_id,#drawn_bank,#chq_number,#bnk_br_code,#ac_number,#drawndate,#amount,#commission_rate,#commission,#order,#recieved_date,#due_date,#reminder_date,#chq_image_frnt,#chq_image_back)";
MySqlCommand cmd = new MySqlCommand(cmdText, con);
cmd.Parameters.AddWithValue("#customer_name", txtCustomerName.Text);
cmd.Parameters.AddWithValue("#national_id", txtIDNumber.Text);
cmd.Parameters.AddWithValue("#drawn_bank", txtDrawnBank.Text);
cmd.Parameters.AddWithValue("#chq_number", txtChqNo.Text);
cmd.Parameters.AddWithValue("#bnk_br_code", txtBnkBrCode.Text);
cmd.Parameters.AddWithValue("#ac_number", TxtAcNo.Text);
cmd.Parameters.AddWithValue("#drawndate", dateTimePickerDrawnDate.Text);
cmd.Parameters.AddWithValue("#amount", TxtAmount.Text);
cmd.Parameters.AddWithValue("#commission_rate", txtCommissionRate.Text);
cmd.Parameters.AddWithValue("#commission", txtCommission.Text);
cmd.Parameters.AddWithValue("#order", Ordercb.Text);
cmd.Parameters.AddWithValue("#recieved_date", dateTimePickerRecieved.Text);
cmd.Parameters.AddWithValue("#due_date", dateTimePickerDue.Text);
cmd.Parameters.AddWithValue("#reminder_date", dateTimePickerReminder.Text);
cmd.Parameters.AddWithValue("#chq_image_frnt", picChqFrnt.Image);
cmd.Parameters.AddWithValue("#chq_image_back", picChqBack.Image);
cmd.ExecuteNonQuery();
MessageBox.Show("Cheque has been inserted to the database");
ClearData();
con.Close();
}
catch (MySqlException x)
{
MessageBox.Show(x.Message);
}
}
Yeah, that's cause order is a reserve word in MySQL and needs to be escaped using backtique like
string cmdText = "INSERT INTO cheque(customer_name, national_id, drawn_bank, ..., `order`,...
That's what the error exactly saying right syntax to use near 'order,recieved_date,
Do yourself a favor and stop using reserve word and key word as table or column name and save yourself from this issues in future

Syntax of SQL Server database connection string in c#

I am beginner at SQL and thank you for your attention. I've created a database (by using "Add new Item" from "Project" menu and adding a "Service Based Database") in Visual Studio 2015 and now I want to connect to it and read or write data on it.
But I don't know how to connect to it by code.
I use the string showed in the connection string when I click on the database in server explorer.
That is here:
Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename="c:\users\soroush\documents\visual studio 2015\Projects\databasetest2\databasetest2\Database1.mdf";Integrated Security=True
But as you know, it cannot be used when I copy and paste it to a string thah can be used in new sqlConnection(connection string), because this string has '\' or ' " '
What's the right string for me to connect to this local database?
Now this is my code but it is not useful:
private void button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(#"Data Source = (LocalDB)\MSSQLLocalDB; AttachDbFilename = c:\users\soroush\documents\visual studio 2015\Projects\databasetest2\databasetest2\Database1.mdf; Integrated Security = True");
con.Open();
string t=#"INSERT INTO Table (Id,name) Values (34, 'John')";
SqlCommand cmd = new SqlCommand(t, con);
cmd.ExecuteNonQuery();
con.Close();
}
private void button2_Click(object sender, EventArgs e)
{
using (SqlConnection con = new SqlConnection(#"Data Source = (LocalDB)\MSSQLLocalDB; AttachDbFilename = c:\users\soroush\documents\visual studio 2015\Projects\databasetest2\databasetest2\Database1.mdf; Integrated Security = True"))
{
con.Open();
string t = "SELECT * From Table";
SqlCommand cmd = new SqlCommand(t, con);
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
MessageBox.Show(reader["Id"].ToString() + reader["name"].ToString());
}
con.Close();
}
}
Thank you for your help
Update: I get another errors in writing and reading table
I think I've connected to my database after using your help. and now I have another error in reading the table. this error points to
SqlDataReader reader = cmd.ExecuteReader();
in my code and says:
An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll Additional information: Incorrect syntax near the keyword 'Table'.
and an error in writing on table points to
cmd.ExecuteNonQuery();
in my code:
An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll Additional information: Incorrect syntax near the keyword 'Table'.
My database has one table named Table that contains two columns: Id(int) and name(nchar10)
The code you're using to connect to your Sql db is .. well ... really old school. We just don't do it like that any more.
So - what can we do instead? Lets use a nice library called Dapper which makes 'talking' to a sql server really easy, simple and safer.
First, install the package Dapper from nuget:
Create a POCO which will represent the data that is returned from the DB.
public class Foo
{
public int Id { get; set; }
public string Name { get; set; }
}
Now update the form code as follows:
private const string _connectionString = #"Data Source = (LocalDB) <snipped..>";
private void button1_Click(object sender, EventArgs e)
{
string query = "INSERT INTO Table (Id,name) Values (34, 'John')";
int rowsInserted;
using (var db = new SqlConnection(_connectionString))
{
rowsInserted = db.Execute(query);
}
if (rowsInserted != 1)
{
// Log/Handle the fact that you failed to insert 1 record;
}
}
private void button2_Click(object sender, EventArgs e)
{
IList<Foo> foos;
using (var db = new SqlConnection(_connectionString))
{
const string query = "SELECT * FROM Table";
// This will always return a list. It's empty or has items in it.
foos = db.Query<Foo>(query).ToList();
}
foreach(var foo in foos)
{
MessageBox.Show($"{foo.Id} - {foo.Name}");
}
}
Is that much cleaner? Yep - I thought so.
Of course, I would never put database code behind a winform event but into a dedicated class, etc. But I guess you're just learning/playing around/experimenting :) :)
Also, I've not put error handling in there, to keep the example smallish.
Change:
string t = "SELECT * From Table";
to:
string t = "SELECT * From [Table]";
and:
string t=#"INSERT INTO Table (Id,name) Values (34, 'John')";
to:
string t=#"INSERT INTO [Table] (Id,name) Values (34, 'John')";
See https://stackoverflow.com/a/695590/34092 and https://learn.microsoft.com/en-us/sql/t-sql/language-elements/reserved-keywords-transact-sql .
my problem has been solved
at first for connection to database I typed an # before connection string and deleted the quotes inside the string as #juergen d said in comments
at second for solving the error in writing and reading the table I typed [ and ] before and after the "Table" as #mjwills said
also #Pure.Krome explained a more professional way to improve the code
thank you every body

Error saving data from textbox to sql server table

I have created a WPF desktop application before and I was able to write up the code to save data from a textbox to a table I created in sql server 2012. I tried to create a WPF Web browser application and the same code was not working to save my data to my sql database. I am now trying to create another WPF desktop application and the same code that worked the last time is not working anymore. Please look at my code and help.
private void savebuyers_Click(object sender, RoutedEventArgs e)
{
string connectionstring = null;
connectionstring = "Data Source=FRANCIS;Initial Catalog=Pam Golding;Integrated Security=SSPI";
SqlConnection con = new SqlConnection(connectionstring);
try
{
string query;
query = "insert into buyers (name,number,email) values ('" + namebuyers.Text + "'," + Convert.ToInt32(numberbuyers) + ",'" + emailbuyers.Text + "')";
SqlCommand command = new SqlCommand(query, con);
message1.Text = "Data Saved Successfully!";
con.Open();
command.ExecuteNonQuery();
con.Close();
}
catch
{
message1.Text = "Error While Saving Data!";
}
}
You have missed the Text property of numberbuyers. So it is unable to cast object of type TextBox to type System.IConvertible.
You can fix it like this:
Convert.ToInt32(numberbuyers.Text)
Also you should always use parameterized queries to avoid Sql Injection.

Unable to connect to any of the specified MySQL hosts

I know that it is an easy problem but I can't find the error. I want to save data in my database. I create a database named "Examen" with Microsoft SQL Server 2008 then in my app in visual studio I make the connection string like this :
string connectionstring = #"Data Source=.\sqlexpress;Initial Catalog=Examen;Integrated Security=True";
Then I use this code to insert data into a "Test" table:
MySqlConnection connection = new MySqlConnection(connectionstring);
MySqlCommand cmd;
connection.Open();
try
{
cmd = connection.CreateCommand();
cmd.CommandText = "Insert into Examen.Test (nom,prenom) values (" + txbnom.Text + "," + txbprenom.Text + ") ";
cmd.ExecuteNonQuery();
MessageBox.Show("ok");
}
catch (Exception)
{
throw;
}
finally
{
if(connection.State == ConnectionState.Open)
{
connection.Close();
}
}
When running this code i had an error when openning the connection
Unable to connect to any of the specified MySQL hosts.
You are mixing MySQL and MSSQL.
Are you sure you want to connect to a MySQL server? Use http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection(v=vs.110).aspx if you would like to connect to MSSQL.
Also you should make yourself familiar with SQL injection

How to insert data from ASP.Net to MS SQL Server?

This question has been asked for several times here. I read posted questions but I still have problem. I'm trying to insert values from ASP.Net form to SQL Server. I created a sample website to work on inserting data into Sql table. SQL Database's name is "TestDatabaseDB" which has one table called "Person". Person table has 4 columns. They are ID, FirstName, LastName, NationalID. The type of ID is "int". I set "Is Identity:Yes". So SQL will assign an ID to each inserted record. It just doesn't work. When I click the button nothing happens. It must insert data into database table or clears the textboxes at least but it doesn't.
I tried
SqlConnection conn= new SqlConnection(#"Data source=.\SQLEXPRESS; AttachDBFilename=""|DataDirectory|\TestWebSiteDB.mdf""; integrated user=true; User Instance=true")
It didn't work. So I changed that into:
SqlConnection conn = new SqlConnection("Data Source=. ; Database=TestWebSiteDB; Integrated Security=true");
Didn't make any difference. Here is my code:
using System;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnRegister_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection("Data Source=. ; Database=TestWebSiteDB; Integrated Security=true");
SqlCommand insert = new SqlCommand("insert into Person(FirstName, LastName, NationalID) values(#Name, #Surname, #ID)" ,conn);
insert.Parameters.AddWithValue("#Name", txtboxName.Text);
insert.Parameters.AddWithValue("#Surname", txtboxFamilyName.Text);
insert.Parameters.AddWithValue("#ID", txtboxNationalCode.Text);
try
{
conn.Open();
insert.ExecuteNonQuery();
}
catch
{
LMsg.Text="Error when saving on database";
conn.Close();
}
txtboxName.Text="";
txtboxFamilyName.Text = "";
txtboxNationalCode.Text = "";
}
}
Any help would be appreciated.
Try this:
protected void Register_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(#"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\DB_Users.mdf;Integrated Security=True");
SqlCommand insert = new SqlCommand("insert into tbl_users(name, username, password,email) values(#name, #username, #password,#email)", conn);
insert.Parameters.AddWithValue("#name", txtname.Text);
insert.Parameters.AddWithValue("#username", txtusername.Text);
insert.Parameters.AddWithValue("#password", txtpassword.Text);
insert.Parameters.AddWithValue("#email", txtemail.Text);
try
{
conn.Open();
insert.ExecuteNonQuery();
lbl_msg.Text = "Register done !";
//lbl_msg.Text = "ثبت نام با موفقیت انجام شد";
}
catch (Exception ex)
{
lbl_msg.Text = "Error: "+ex.Message;
//lbl_msg.Text = "خطا در ارتباط با پایگاه داده";
conn.Close();
}
}
It works for me.
You need to track what error you are getting as follows. Because it is not possible to help you without the actual error.
catch(Exception ex)
{
LMsg.Text=ex.Message;
}
Also you need to use finally in your code for closing connection rather than closing it into the catch block.
finaly
{
conn.Close();
}
check your connection string. in conn.open() you get exception ?
To create a data connection to a SQL Server database
In Server Explorer/Database Explorer click Connect to Database.
In the Choose Data Source dialog box, select Microsoft SQL Server, and then click OK.
If the Add Connection dialog box opens, and the Data source is not Microsoft SQL Server, click Change to open the Choose/Change Data Source dialog box
. For more information, see Choose/Change Data Source Dialog Box.
Select a server name from the drop-down list, or type the name of the server where the database you want to access is located.
Based on the requirements of your database or application, select either Windows Authentication or use a specific user name and password to log on to the SQL Server (SQL Server Authentication).
For more information, see Add/Modify Connection (Microsoft SQL Server).
Select the database you want to connect to from the drop-down list.
Click OK.
then copy generated connection string to your program.
when you install sql server the server name and the setting you choose for installing .affect your connection string.
for more inforamtion on installing sql server see the
installing sql server express edition
and also check this for connecting asp.net application to sql server
Asp.net connection to SQL Server
Actually the list view has a default method call onsorting. It will automatically sort the list view. onsorting will call the function as below.The function no need put any statement.
protected void Sorting(object sender,ListViewSortEventArgs e)
{
}
For the link button in list view u just simply put the tag like that:
<asp:ListView ID="DisplayContent" runat="server" onSorting="Sorting">
<asp:LinkButton ID="Name" runat="server" CommandName="Sorting" CommandArgument="Name" Text="Name" />
Try following steps:
Step1: Instead of putting you query in your C# file, declare a stored procedure for it like bellow:
CREATE PROCEDURE [dbo].[ADD_PERSON_SP]
/*Type of this variables should be their column types*/
#firstName varchar(MAX),
#lastName varchar(MAX),
#nationalID varchar(MAX)
AS
BEGIN
INSERT INTO [dbo].[Person] (FirstName, LastName, NationalID)
VALUES (#firstName,#lastName,#nationalID)
END
Step2: Using Stored Procedure where you need:
SqlConnection con = new SqlConnection(connectionString);
SqlCommand com = new SqlCommand("ADD_PERSON_SP", con);
com.Parameters.AddWithValue("#firstName", txtboxName.Text);
com.Parameters.AddWithValue("#lastName", txtboxFamilyName.Text);
com.Parameters.AddWithValue("#nationalID", txtboxNationalCode.Text);
com.CommandType = CommandType.StoredProcedure;
try
{
con.Open();
com.ExecuteNonQuery();
}
catch (Exception)
{
throw;
}
finally
{
if (con.State == ConnectionState.Open)
con.Close();
}
Keep in mind to:
Do not put db related stuffs in your C# files
Try to choose better names for your variables(specially for controls)
This may help you with connectionString
I hope that help
protected void btnRegister_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection("Data Source=. ; Database=TestWebSiteDB; Integrated Security=true");
SqlDataAdapter dap = new SqlDataAdapter("insert into Person(FirstName, LastName, NationalID) values(#Name, #Surname, #ID)", con);
dap.InsertCommand(txtboxName.Text, txtboxFamilyName.Text,txtboxNationalCode.Text);
txtboxName.Text="";
txtboxFamilyName.Text = "";
txtboxNationalCode.Text = "";
}

Categories

Resources