'Keyword not supported error' Using Dot Connect and MySQL - c#

I am trying to connect a MySQL database to a winform using C#. I am receiving this error: System.ArgumentException: 'Keyword not supported: 'host'. I have already checked that the database has a proper connection using the test connection and the connection string that I am using is the one provided to me using the server explorer. After doing research, the issue lies in either the references I'm using or in the app.config itself. Does anyone have any experience with this issue or can offer any feedback? Here is the very basic code snippet i'm working with:
using System;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace savetodatabasepractice
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
using (SqlConnection conn = new SqlConnection())
{
conn.ConnectionString = "User Id=XXXXXX;Host=localhost;Database=XXXXXX";
SqlCommand insertCommand = new SqlCommand("INSERT INTO tbl_newdata (ID, Temperature, Humidity) VALUES (1, 72, 34)", conn);
}
}
}
}
I am using Visual Studio 2017, DotConnect for MySQL, MySQL server, and Wamp Connect. Thank you!
EDIT: After reading documentation a sample c# program with this format should look like
using System;
using System.Windows.Forms;
using Devart.Data.MySql;
namespace savetodatabasepractice
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
MySqlConnection conn = new MySqlConnection("User Id=root;Host=localhost;Database=XXXXXX;");
MySqlCommand cmd = new MySqlCommand();
cmd.CommandText = "INSERT INTO tbl_newdata (ID, Temperature, Humidity) VALUES (1,73,32)";
cmd.Connection = conn;
conn.Open();
try
{
int aff = cmd.ExecuteNonQuery();
MessageBox.Show(aff + " rows were affected.");
}
catch
{
MessageBox.Show("Error encountered during INSERT operation.");
}
finally
{
conn.Close();
}
}
}
}
The key is to not only use the correct reference but to also download the correct package on nuget. Easy to forget for beginners!

What??? you are using DotConnect for MySQL but you use a SqlConnection class. That's the issue here cause SqlConnection is for SQLServer. You should use using Devart.Data.MySql.MySqlConnection instead.
using (SqlConnection conn = new SqlConnection())
{
Check the documentation first which says everything. https://www.devart.com/dotconnect/mysql/docs/

Related

C# software wont connect to my localhost mysql Xampp says sqlException was unhandled

I'm done designing my project software that passes information in my software textbox to my local mysql xampp database.
im have this error message
Please help with the code below. What am i getting wrong from the code below?
I have two textboxes namely "seed" and "password" and button "encrypt" and "decrypt"
namespace seed
{
public partial class CryptSeed : Form
{
public CryptSeed()
{
InitializeComponent();
}
SqlConnection con = new SqlConnection("server=localhost;user id=seedcrypt;persistsecurityinfo=True;database=seed;");
private void Form1_Load(object sender, EventArgs e)
{
con.Open();
string query = "INSERT INTO info ('id','seed','password','ip') VALUES (NULL,'"+seed.Text+ "','" +password.Text+ "',NULL)";
SqlDataAdapter SDA = new SqlDataAdapter(query, con);
SDA.SelectCommand.ExecuteNonQuery();
con.Close();
MessageBox.Show("INSERTED SUCCESSFULLY !!! ");
}
}
}
If you are connecting to mysql database you got it all wrong.First you need mysqlconnector for c#.
Second what exactly are you trying to do?save?read?
public partial class CryptSeed : Form
{
public CryptSeed()
{
InitializeComponent();
}
//you will need to specify the port Mysql uses:3306
private void Form1_Load(object sender, EventArgs e)
{
// If you are saving data you cant do it here.
// But still will show you how to do it in a button //click
//event.
}
private void button1_Click(object sender,EventArgs e)
{MySqlConnection con = new MySqlConnection("server=localhost;port=3306; username=seedcrypt;database=seed;password=xxxxxxx");
string query = "INSERT INTO
info('id','seed','password','ip') VALUES
(NULL,'"+seed.Text+ "','" +password.Text+ "',NULL)";
con.Open();
MysqlCommand cmd = new
MysqlCommand(query,con);
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("INSERTED SUCCESSFULLY !!!
");
}
}
}

How do i fill combo boxes with data from mysql in visual c#

I've tried every single solution ive found on here and still cant get it to work
Currently all i get is a blank combo box regardless of what i change, can anyone see where im going wrong for title? (Yet to try price due to success with my titles combo box)
I'm trying to pull Title and Price out of my Game_Details table in the Aliena_Store MySQL database.
using System;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
using System.Data;
using System.Data.SqlClient;
using System.Data.Common;
namespace Aliena_Store
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
private void Form2_Load(object sender, EventArgs e)
{
}
private void Game_List_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
MySqlConnection connection = new MySqlConnection
"server=localhost;user=root;database=Aliena_Store
;port=3306;password=Blackie");
string selectQuery = "SELECT Title,Price FROM
Aliena_Store.Game_Details";
connection.Open();
MySqlCommand command = new MySqlCommand(selectQuery, connection);
MySqlDataReader reader = command.ExecuteReader();
int i = 0;
while (reader.Read())
{
Game_List.Items.Insert(i, reader.GetString("Title"));
i++;
}
connection.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void Game_Quantity_TextChanged(object sender, EventArgs e)
{
}
private void Game_Price_SelectedIndexChanged(object sender, EventArgs e)
{
}
}
}
Your SQL may not be returning what you think
"Select Title * ...." you probably didnt want that "*" in there. Are you getting a number of blank entries or just no entries?
You do know your code is only running if you could change items on the drop down right?
If your dropdownlist is Game_List, then you should try :
int i =0
while (reader.Read())
{
Game_List.Items.Insert(i, reader.GetString("Title"));
i++
}

Insert into database c# connection string error

i am encountering an error when trying to set up an insert command into my database, it appears to be with the connection string. I am extremely new to all this and am trying to get the correct code in order to upload into my database and assume that the syntax i am using may be wrong and the cause of the error.
Here is the code a little bit clearer:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
namespace ComputingProjectwh.TestPages._1._Further_Mechanics
{
public partial class Moments_and_Energy_Test1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Submit_Click(object sender, EventArgs e)
{
if (!this.IsValid)
return;
int score = 0;
List<RadioButtonList> list = new List<RadioButtonList>() { RadioButtonList1, RadioButtonList2, RadioButtonList3, RadioButtonList4, RadioButtonList5, RadioButtonList6, RadioButtonList7, RadioButtonList8, RadioButtonList9, RadioButtonList10 };
foreach (var element in list)
{
if (element.SelectedValue == "Correct")
{
score++;
}
}
Response.Write("you scored: " + score);
Button1.Visible = false;
if (score != 0);
{
SqlConnection sqlConnection1 = new SqlConnection (#"Data Source=(LocalDb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\aspnet-ComputingProjectwh-20170404101246.mdf;InitialCatalog=aspnet-ComputingProjectwh-20170404101246;IntegratedSecurity=True");
System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand();
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandText = "INSERT AspNetUserTestScores (Id, MomentAndEnergyTestScore) VALUES (Id, score)";
cmd.Connection = sqlConnection1;
sqlConnection1.Open();
cmd.ExecuteNonQuery();
sqlConnection1.Close();
}
}
}
}
I am really not sure what the problem is and cant seem to find an answer on the internet. Any help would be greatly appreciated.
When connecting to MSSQL, there is no initialcatalog, You are using a wrong connection string.
This is the correct syntax:
Server=myServerAddress;Database=myDataBase;User Id=myUsername;Password=myPassword;
Or in your case, for trusted connection:
Server=myServerAddress;Database=myDataBase;Trusted_Connection=True;
With your data:
SqlConnection sqlConnection1 = new SqlConnection("Server=LocalDb;Database=aspnet-ComputingProjectwh-20170404101246.mdf;Trusted_Connection=True;");
InitialCatalog is two separate words initial catalog.

How to include this code in a C# program

I am running into problems with my Database not opening because it is already, apparently, open.
Unable to copy file "j:...\KAELC_DB.mdf" to "bin\Debug\KAELC_DB.mdf".
The process cannot access the file 'j:...\KAELC_DB.mdf' because it is
being used by another process.
Unable to copy file "j:...\KAELC_DB_log.ldf" to
"bin\Debug\KAELC_DB_log.ldf". The process cannot access the file
'j:...\KAELC_DB_log.ldf' because it is being used by another process.
I found a reply to an old question on StackExchange, linked to here https://stackoverflow.com/a/3998383, by "Justin", which looks to resolve that problem (and I have also read in other places that "using" is one of the most efficient ways of programming in C#) but how do I use this in my code ?
I have created a small Project that does nothing but allow me to press a button in order to process a SQL statement, but I'm confused as to what "Justin" means by "Use the connection" ... how do I put SQL statements into this code ?!?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace MySqlTest
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
//Open SQL File
using (SqlConnection conn = SqlHelper.GetConn())
{
// Use the connection <<< How ?!?!?
}
}
private void button2_Click(object sender, EventArgs e)
{
//Insert Record Into SQL File
}
private void button3_Click(object sender, EventArgs e)
{
//Read Record From SQL File
}
private void button4_Click(object sender, EventArgs e)
{
//Read All Records From SQL File
}
private void button5_Click(object sender, EventArgs e)
{
//Delete Record From DQL File
}
private void button6_Click(object sender, EventArgs e)
{
//Close SQL File
}
private void button7_Click(object sender, EventArgs e)
{
//Quit
this.Close();
}
class SqlHelper
{
public static SqlConnection GetConn()
{
SqlConnection returnValue = new SqlConnection(#"Data Source=MEDESKTOP;AttachDbFilename=|DataDirectory|\SqlTestDB.mdf;Initial Catalog=MySqlDB;Integrated Security=True");
returnValue.Open();
return returnValue;
}
}
}
}
if all you want to do is run an SQL command, use an SQLCommand object. (MSDN docs here)
here is the sample code from the article...
private static void ReadOrderData(string connectionString)
{
string queryString =
"SELECT OrderID, CustomerID FROM dbo.Orders;";
using (SqlConnection connection = new SqlConnection(
connectionString))
{
SqlCommand command = new SqlCommand(
queryString, connection);
connection.Open();
SqlDataReader reader = command.ExecuteReader();
try
{
while (reader.Read())
{
Console.WriteLine(String.Format("{0}, {1}",
reader[0], reader[1]));
}
}
finally
{
// Always call Close when done reading.
reader.Close();
}
}
}
things to note:
uses a SqlConnection object with a Using block
uses an SqlCommand object
uses an SqlDataReader object
explicitly closes the SqlConnection with finished with it

An unhandled exception of type 'System.StackOverflowException' occurred in GUI_Login.DLL

I am changing a console app login over to a web based application and recieve the following error about an Unhandled exception.
In the console app I have the following line of code which resides in the StoredProcDemo class:
StoredProcDemo spd = new StoredProcDemo();
In the Web Application I have:
Login spd = new Login();
I am not sure what to change it over to. Could someone shed some insight thanks and maybe why? Thanks so much.
Here is the full code if needed.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Data.Sql;
using System.Data.SqlTypes;
namespace GUI_Login
{
public partial class Login : System.Web.UI.Page
{
SqlConnection conn = null;
SqlParameter parmReturnValue;
Login spd = new Login();
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnLogin_Click(object sender, EventArgs e)
{
RunStoredProcParams();
}
public void RunStoredProcParams()
{
//run simple stored procure
spd.RunStoredProcParams();
int Result;
Result = -1;
conn = conn = new SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename=c:\\Program Files\\Microsoft SQL Server\\MSSQL10.SQLEXPRESS\\MSSQL\\DATA\\UserDB.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True; Integrated Security=SSPI");
conn.Open();
try
{
//create and open a connection object
conn = conn = new SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename=c:\\Program Files\\Microsoft SQL Server\\MSSQL10.SQLEXPRESS\\MSSQL\\DATA\\UserDB.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True; Integrated Security=SSPI");
conn.Open();
//Create the command object indentifying the stored procedure
SqlCommand cmd = new SqlCommand("PassParamUserID", conn);
//set the command object so it knows to execute a stored procedure
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("#FirstName", txtUserName.Text));
parmReturnValue = cmd.Parameters.AddWithValue("#UserId", SqlDbType.Int);
parmReturnValue.Direction = ParameterDirection.ReturnValue;
cmd.ExecuteNonQuery();
Result = Convert.ToInt32(cmd.Parameters["#UserId"].Value);
conn.Close();
// lblResult.Text = Result;
if (Result > 0)
{
lblResult.Text = ("User does exist in database");
}
else if (Result < 0)
{
lblResult.Text = ("Denied, try another user name");
}
}
finally
{
if (conn != null)
{
conn.Close();
}
}
}
Even ignoring RunStoredProcParams you'll get a stack overflow as soon as you try to create a new instance:
public partial class Login : System.Web.UI.Page
{
// Removed extraneous stuff...
Login spd = new Login();
}
Why do you want every instance of Login to have a reference to another instance of Login, which it creates immediately?
Basically the constructor is going to be called recursively until it goes bang.
What are you trying to do here, and why? In the console app you may well be creating an instance of StoredProcDemo, but I'm sure it wouldn't be within StoredProcDemo itself (as an instance variable initializer). Perhaps it's in Program or something similar? That would make more sense.
You run RunStoredProcParams() recursively indefinitely.
Comment out this line:
spd.RunStoredProcParams();
Also comment this one:
Login spd = new Login();

Categories

Resources