Connection not working with localdb in visual studios - c#

Sorry to be asking this I know there are many other questions and have tried to use the solutions provided but I just cannot get my code to work. Thanks for looking!
Connection String as shown in Properties:
Data
Source=(LocalDB)\v11.0;AttachDbFilename="C:\Users\Jacob\Documents\Visual
Studio
2013\Projects\WindowsFormsApplication2\WindowsFormsApplication2\ChatDB.mdf";Integrated
Security=True
Connection string in app.config:
Data
Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\ChatDB.mdf;Integrated
Security=True
Error: An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll
Additional information: Incorrect syntax near the keyword 'User'.
Code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
//NC-1 More namespaces.
using System.Data.SqlClient;
using System.Configuration;
namespace WindowsFormsApplication2
{
public partial class SignUp : Form
{
string connstr = ConfigurationManager.ConnectionStrings["WindowsFormsApplication2.Properties.Settings.ChatDBConnectionString"].ToString();
public SignUp()
{
InitializeComponent();
}
private void label1_Click(object sender, EventArgs e)
{
}
private void SubmitBtn_Click(object sender, EventArgs e)
{
string Name = NameText.Text;
string Pwd = PwdText.Text;
//make sure they have entered text
if (Name.Length > 0 && Pwd.Length > 0)
{
SqlConnection conn = new SqlConnection(connstr);
//NC-10 try-catch-finally
try
{
//NC-11 Open the connection.
conn.Open();
SqlCommand insert = new SqlCommand();
insert.Connection = conn;
insert.CommandText = "INSERT INTO [User] (Name,Password) VALUES ('" + Name + "','" + Pwd + "')";
insert.ExecuteNonQuery();
MessageBox.Show("Congrats!!!");
}
catch
{
//NC-14 A simple catch.
MessageBox.Show("User was not returned. Account could not be created.");
}
finally
{
//NC-15 Close the connection.
conn.Close();
}
}
//if no text make them enter
else
{
MessageBox.Show("Please enter Text in both fields.");
}
}
}
}
Again thank you for looking.

The problem is your SQL Query because you use a Reserved Keywords
Try to change your table name to tblUser.
I also suggest to use a parameterize query to prevent future SQL injection: (For Example)
#"INSERT INTO [User] (Name,Password) VALUES (#Name, #Password);"

Related

C#: MySQL Exception was unhandled

An unhandled exception of type MySql.Data.MySqlClient.MySqlException occurred in MySql.Data.dll
Additional information:
Access denied for user 'groupdes_ling'#'60.50.32.226' (using password: YES)
This error occurs whenever i'm trying to run my program. The coding is pasted below:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
namespace GroupDesignProject
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
string MyConnectionString = "Server=31.220.105.189;Database=groupdes_GDP;Uid=groupdes_ling;Pwd=0164851286;";
MySqlConnection connection = new MySqlConnection(MyConnectionString);//create connection
MySqlCommand cmd;
connection.Open();//connect to database
//write INSERT command and execute
cmd = connection.CreateCommand();//create command
cmd.CommandText = "INSERT INTO trial (Name)values ('" + textBox1.Text + "');";
cmd.ExecuteNonQuery();
//disconnect from database
if (connection.State == ConnectionState.Open)
{
connection.Close();
}
}
}
}
I still can't manage to solve this error. Thanks for the help
You need to add permissions for that user/host/password combination to the MySQL instance. For example;
GRANT ALL ON *.* to 'groupdes_ling'#'60.50.32.226' IDENTIFIED BY 'Password';

C# Mysql login error

I am working with C# (visual studio 2012 professional) and Mysql . I trying to create a login form, where a user needs to insert the username and password:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
namespace Dark_Heresy
{
public partial class Login_Menu : Form
{
private MySqlConnection connection = new MySqlConnection();
public Login_Menu()
{
InitializeComponent();
TextPassword.PasswordChar = '*';
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void btn_Login_Click(object sender, EventArgs e)
{
try
{
string connectionString = "datasource = localhost; port = 3306; username = root; password = Mypass;";
using(MySqlConnection myConn = new MySqlConnection(connectionString))
using(MySqlCommand selectCommand = new MySqlCommand())
{
selectCommand.CommandText = ("SELECT COUNT(1) FROM dark_heresy.users WHERE users_=#User and password_=#Password;");
selectCommand.Connection = myConn;
selectCommand.Parameters.Add(new MySqlParameter("User", MySqlDbType.VarChar).Value = TextUserName.Text);
selectCommand.Parameters.Add(new MySqlParameter("Password", MySqlDbType.VarChar).Value = TextPassword.Text);
myConn.Open();
var ret = selectCommand.ExecuteScalar();
var count = Convert.ToInt32(ret);
if (count == 1)
{
this.Hide();
Menu mn = new Menu();
mn.ShowDialog();
}
else if (count > 1)
{
MessageBox.Show("Duplication of Username and Password... Access Denied");
}
else
{
MessageBox.Show("Incorrect Username and/or Password");
}
}
}
catch (Exception exp)
{
MessageBox.Show("Error: \r\n" + exp);
}
}
}
}
I don't get any syntax errors, but when i run this code i recieve this error:
MySql.Data.MySqlClient.MySqlException(0x80004005):
Only MySqlParameter objects may be stored at MySql.Data.MySqlClient.MySqlParameterCollection.Add(Object value)
at Dark_Heresy.Login_Menu.btn_Login_Click(Object sender, EventArgs e)
I know for security reason is it a better idea to use mysql.user table instead of dark_heresy.users table for user check, but right now is for testing purpose.
What is wrong with the code?
it says there is an error in line 39
I think your parameter syntax is wrong.
= operator returns the right side value also instead of just assigning. That's why;
new MySqlParameter("User", MySqlDbType.VarChar).Value = TextUserName.Text;
expression returns TextUserName.Text as a value and your parameter part will be like;
selectCommand.Parameters.Add(TextUserName.Text);
The right syntax seems;
selectCommand.Parameters.Add("#User", MySqlDbType.VarChar).Value = TextUserName.Text;
selectCommand.Parameters.Add("#Password", MySqlDbType.VarChar).Value = TextPassword.Text;
And please, don't store your passwords as a plain text.
Read: Best way to store password in database

connecting to database - connectionString connect.Open() error

So I am trying to run a query in a database that searches the database table from a textbox input. My code is
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace Query
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void employeeBindingNavigatorSaveItem_Click(object sender, EventArgs e)
{
this.Validate();
this.employeeBindingSource.EndEdit();
this.tableAdapterManager.UpdateAll(this.personnelDataSet);
}
private void Form1_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'personnelDataSet.employee' table. You can move, or remove it, as needed.
this.employeeTableAdapter.Fill(this.personnelDataSet.employee);
}
private void btnExit_Click(object sender, EventArgs e)
{
this.Close();
}
string connectionString = "Server=myServerAddress;Database=myDataBase;Trusted_Connection=True;";
private void btnSearch_Click(object sender, EventArgs e)
{
string commandText = "SELECT employeeID, name, position, hourlyPayRate " +
"FROM dbo.employee WHERE name LIKE '%'+ #Name + '%'";
using (SqlConnection connection = new SqlConnection(connectionString))
{
//Create a SqlCommand instance
SqlCommand command = new SqlCommand(commandText, connection);
//Add the parameter
command.Parameters.Add("#Name", SqlDbType.VarChar, 20).Value = textBox1.Text;
//Execute the query
try
{
connection.Open();
command.ExecuteNonQuery();
}
catch
{
//Handle excepetion, show message to user...
MessageBox.Show("Error bitch!");
}
finally
{
connection.Close();
}
}
}
}
}
When I take the catch out I can see the error occurs at connection.Open(). The error takes a while to happen which makes me wonder whether there is an issue with string connectionString = "Server=myServerAddress;Database=myDataBase;Trusted_Connection=True;";
This is the error that I receive:
An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll
You need to validate the connection string. If Open() is throwing an SqlException then the connection string is invalid. To enable you to establish the exact form of the connection string you require, take a look at connectionstrings.com.
As to why the exception is showing as unhanded, you need to 'consume' the exception as follows:
try
{
connection.Open();
command.ExecuteNonQuery();
}
catch (Exception e)
{
// Handle excepetion, show message to user...
MessageBox.Show(e.Message);
}
I hope this helps.
Check this out:
string connectionString = "Server=.\InstanceName;Database=myDataBase;Integrated Security=True;";
Also
string commandText = "SELECT employeeID, name, position, hourlyPayRate
FROM dbo.employee WHERE name LIKE '%#Name%'";
try:
string connectionString = "Data Source=myServerAddress;Initial Catalog=myDataBase;User id=myUser;Password=myPAss;Connect Timeout=15;Integrated Security=false";
Try declaring your connection string inside the event.
An alternate method is to link your database through web.config as follows:
<connectionStrings>
<connectionString="Data Source=(localdb)\v11.0;Initial Catalog=DBName;Integrated Security=True" providerName="System.Data.SqlClient"/>
</connectionStrings>
And then the connection string can be as:
string cs = ConfigurationManager.ConnectionStrings["DBName"].ConnectionString;

How to fix 'System.Data.OleDb.OleDbException'?

first off sorry to ask how to fix this error (i know its a common question) but i am quite new to C# and I cannot seem to find a solution for it.
I am making a windows form that imports data from an excel file and displays it in a DataGridView. When executing I get the error:
"An unhandled exception of type 'System.Data.OleDb.OleDbException'
occurred in System.Data.dll Additional information: No value given for
one or more required parameters."
Here is my code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.OleDb;
using System.IO;
namespace WindowsFormsApplication2
{
public partial class CurrentOrders : Form
{
public CurrentOrders()
{
InitializeComponent();
}
private void CurrentOrders_Load(object sender, EventArgs e)
{
}
private void BackBtn_Click(object sender, EventArgs e)
{
NewOrder NewOrd = new NewOrder();
this.Hide();
NewOrd.Show();
}
private void DataGridViewLOG_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Tombies\Documents\Visual Studio 2013\Projects\WindowsFormsApplication2\WindowsFormsApplication2\PCSsheet.xls" + #";Extended Properties=""Excel 12.0;HDR=Yes;IMEX=1;ImportMixedTypes=Text;TypeGuessRows=0""";
OleDbCommand command = new OleDbCommand
(
"SELECT DATE, CUSTOMER, PO, COMMENTS, PCS FROM [LOG$]", conn
);
DataSet DsOrderLOG = new DataSet();
OleDbDataAdapter Adapter = new OleDbDataAdapter(command);
conn.Open();
Adapter.Fill(DsOrderLOG);
conn.Close();
DataGridViewLOG.DataSource = DsOrderLOG.Tables[0];
}
}
}
I know it has something to do with the 'Adapter.Fill' at the bottom, but from there on I'm lost.
Any help is appreciated!
Date is probably the culprit. Try putting it (an all other column names, for that matter) in brackets:
"SELECT [DATE], [CUSTOMER], [PO], [COMMENTS], [PCS] FROM [LOG$]", conn

restriction error on messages between SQLSERVER and dot.net

Update:
I tried to run this on a local instance of sql-server and sadly it worked!!!
now I know that the code is right and there is some kind of DBA restriction I need to find (and ask the DBA to remove)
Any ideas?
using System;
using System.Collections.Generic;
using System.Text;
using System.Data.SqlClient;
using System.Data;
namespace testDBMessages
{
public class CGeneral
{
// Declare and instantiate connection
private static Form1 caller;
public CGeneral(Form1 caller1)
{
caller = caller1;
string connString = "server=(local)\\SQLEXPRESS;database=tests;Integrated Security=SSPI";
SqlConnection cn = new SqlConnection(connString);
cn.InfoMessage += new SqlInfoMessageEventHandler(CnInfoMessage);
cn.FireInfoMessageEventOnUserErrors = true;
SqlCommand cmd = new SqlCommand();
String sql = "dbo.fillTables";
cmd.Connection = cn;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = sql;
cmd.Parameters.Add(new SqlParameter("#test", 6));
try
{
cn.Open();
SqlDataReader sdr;
sdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
}
catch (SqlException ex)
{
Console.WriteLine(ex.Message);
}
finally
{
cn.Close();
}
}
static void CnInfoMessage(object sender, SqlInfoMessageEventArgs ev)
{
foreach (SqlError err in ev.Errors)
{
Console.WriteLine("Message- " + err.Message);
caller.addMessage(err.Message);
}
}
}
}
form code
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace testDBMessages
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
CGeneral a = new CGeneral(this);
}
private void Form1_Load(object sender, EventArgs e)
{
Application.DoEvents();
}
public void addMessage(string msg)
{
listView1.Items.Add(msg);
listView1.Refresh();
}
}
}
stored procedure
ALTER PROCEDURE [dbo].[fillTables]
(
#test smallint
)
AS
BEGIN
declare #counter as int
SET #counter=1
while #counter<100
BEGIN
Insert into tests.dbo.tToFill (id,description,testNum)
Values (#counter,'test_1',#test)
RAISERROR ('RECORD NUM %d',10,1,#counter)
SET #counter=#counter+1
END
END
GO
Does the user that you connect to your database as using the Integrated security have EXECUTE permission on the stored procedure (dbo.filltables) as that indicates only dbo (database owner) has full permissions on the procedure.
You will need to grant permissions for anyone that wants to use it. Be careful of granting EVERYONE the right if security is a concern.
Your RAISERROR with severity of 10 is classed as a warning so does not flow to client code.
Use 16, which is defined as "Indicates general errors that can be corrected by the user"
(Edit) I'm sure that used to be different...
RAISERROR ('RECORD NUM %d',16,1,#counter)

Categories