Unable to insert data into MySQL table via ASP.NET Web Application - c#

I have installed MySQL on my local computer and am trying to enable insertion of data to a created MySQL table from my ASP.NET web application on Visual Studio 2017. I've managed to set up a MySQL connection successfully and created table called 'events'.
Initially, I do not have any syntax or system errors, using the code below, but whenever I try to insert data from my web form upon clicking, no data is inserted into the MySQL table. Any advice if there is anything wrong in my code or any other file configurations?
Later, after I tried installing Connector for .NET, I still cannot insert data into the MySql and I get the below errors in namespace MySqlConnection stating 'the-type-mysqlconnection-exists-in-both-mysql-data-issue' as seen below
Any advice what can be corrected to be able to insert data into my table? Is it in my Insert code or does problem lie elsewhere? Below are my code:
AddEvent.aspx.cs:
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using MySql.Data.MySqlClient;
namespace Prototype3
{
public partial class AddEvent : System.Web.UI.Page
{
//convert event date input into DateTime format on back-end of page
string dateStr = dateinput1.Value;
DateTime date;
//Saving data on added event into MySQL database
string constring = "server=localhost;user id=***********;
password=***********!;
persistsecurityinfo=True;database=homesecretary";
//Connection to database below-check!!
string Query = "INSERT into events (eventTitle) VALUES
('"+tb_eventTitle.Text+"')"; //Parse date input from jQuery
datepicker
MySqlConnection connDataBase = new MySqlConnection(constring);
MySqlCommand cmdDataBase = new MySqlCommand(Query, connDataBase);
MySqlDataReader myReader;
try
{
connDataBase.Open();
myReader = cmdDataBase.ExecuteReader();
connDataBase.Close();
}
Web.config:
<configuration>
<connectionStrings>
<add name="homesecretaryConnectionString"
connectionString="server=localhost;user
id=********; password=********; persistsecurityinfo=True;
database=homesecretary" providerName="MySql.Data.MySqlClient" />
</connectionStrings>
.....
</configuration>

You are doing a very basic/fundamental mistake here.
The MySqlDataReader purpose is to use when we are selecting data. You need to insert data not query so it should be calling ExecuteNonQuery() method:
// for inserts/updates queries
cmdDataBase.ExecuteNonQuery()
Please refer to the following docs for seeing an example on how to insert data in ADO.NET:
MSDN - Insert New Records in to Database
Note: Please don't do string concatenation for creating queries as it is not a good practice instead of that you should be using Parameterized queries. See an example here

To update/insert the data you may need to use ExecuteNonQuery and to fill the DataSet you may use MySqlDataAdapter as follow:
private static string _DBConnectionString = string.Empty;
public static int SetData(string sqlQuery)
{
int iReturn = -1;
try
{
MySqlCommand cmd = new MySqlCommand(sqlQuery);
using (MySqlConnection conn = new MySqlConnection(DBConnectionString))
{
if (conn.State != ConnectionState.Open)
conn.Open();
cmd.Connection = conn;
iReturn = cmd.ExecuteNonQuery();
if (conn.State == ConnectionState.Open)
conn.Close();
}
}
catch (Exception E)
{
iReturn = -1;
}
return iReturn;
}
public static object GetData(string sqlQuery)
{
DataSet dtSet = new DataSet();
try
{
MySqlCommand cmd = new MySqlCommand(sqlQuery);
MySqlDataAdapter adpt = new MySqlDataAdapter();
using (MySqlConnection conn = new MySqlConnection(DBConnectionString))
{
if (conn.State != ConnectionState.Open)
conn.Open();
cmd.CommandTimeout = 0;
adpt.SelectCommand = cmd;
cmd.Connection = conn;
adpt.Fill(dtSet);
if (conn.State == ConnectionState.Open)
conn.Close();
}
}
catch (Exception E)
{
}
return dtSet;
}

Related

Database connection doesn't work C#

I'm working on a program in C#. I created a database with MySQL on phpMyAdmin and I want to connect this database with my program.
After the connection I have to insert, update, delete and view all the data, but I have a problem: the connection doesn't work.
I post here my code for the connection:
public static string StringaConnessione = "Data Source=localhost;Database=agility;userid=root;password='';";
public static MySqlConnection Connessione = new MySqlConnection(StringaConnessione);
When I write the code for the insert button I have another problem (is certainly for the database)
Connessione.Open();
SQLDataAdapter SDA=new SqlDataAdapter("INSERT INTO GARA(nome_gara,giudice,località,data,tpsopm,tpmopm,tpstot,tpmtot)VALUES('"+textBox1.Text+"','"+textBox2.Text+"','"+textBox3.Text+"','"+textBox4.Text+"','"+textBox5.Text+"','"+textBox6.Text+"','"+textBox7.Text+"','"+textBox8.Text+"')",Connessione);
SDA.SelectCommand.ExecuteNonQuery();
Connessione.Close();
MessageBox.Show("Dati salvati correttamente!");
May you help me, please? Thank you!
You can't use a SqlDataAdapter to talk to MySQL as that class is designed for use with Sql Server.
Use the MySqlDataAdapter instead.
You have so many problems with your code:
1) You are using static connection, there is Connection pool and it is your friend.
2) You are not using your connection in using block or in try/catch/finally/block
to ensure closing of connection on exception.
3) Blocker problem: You are using SqlDataAdapter instead of MySqlDataAdapter
4) Blocker problem You should define your Insert query in InsertCommand of the DataAdapter, it will not work with SelectCommand. Even better just use MySqlCommand and ExecuteNonQuery on it.
5) You are not protected from Sql Injection(Use MySqlCommand.Parameters)
6) Bad formatting of your variables, textboxes and db fields.
How your code will look optimally:
public static string connetionString= "Data Source=localhost;Database=agility;userid=root;password='';";
public void SomeMethod()
{
using(MySqlConnection conn = new MySqlConnection(connetionString));
{
conn.Open();
string query = #"INSERT INTO GARA
(nome_gara, giudice, località, data, tpsopm, tpmopm, tpstot, tpmtot)
VALUES
(#Param1, #Param2, #Param3, #Param4, #Param5, #Param6, #Param7, #Param8)";
MySqlCommand cmd = new MySqlCommand(#"query", conn);
cmd.Parameters.AddWithValue("#Param1", textBox1.Text);
cmd.Parameters.AddWithValue("#Param2", textBox2.Text);
cmd.Parameters.AddWithValue("#Param3", textBox3.Text);
cmd.Parameters.AddWithValue("#Param4", textBox4.Text);
cmd.Parameters.AddWithValue("#Param5", textBox5.Text);
cmd.Parameters.AddWithValue("#Param6", textBox6.Text);
cmd.Parameters.AddWithValue("#Param7", textBox7.Text);
cmd.Parameters.AddWithValue("#Param8", textBox8.Text);
cmd.ExecuteNonQuery();
}
}
i think you should discard all your code.
and find a valid one to start
for example this
http://roboardgod.blogspot.hk/2013/08/cmysql.html
you may need to add the reference MySql.Data.MySqlClient manually. check this post to add the reference
How do I add a reference to the MySQL connector for .NET?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MySql.Data.MySqlClient;
namespace MySQLtest
{
class Program
{
static void Main(string[] args)
{ string dbHost = "";//db address, for example localhost
string dbUser = "";//dbusername
string dbPass = "";//dbpassword
string dbName = "";//db name
string connStr = "server=" + dbHost + ";uid=" + dbUser + ";pwd=" + dbPass + ";database=" + dbName;
MySqlConnection conn = new MySqlConnection(connStr);
MySqlCommand command = conn.CreateCommand();
conn.Open();
String cmdText = "SELECT * FROM member WHERE level < 50";
MySqlCommand cmd = new MySqlCommand(cmdText, conn);
MySqlDataReader reader = cmd.ExecuteReader(); //execure the reader
while (reader.Read())
{
for (int i = 0; i < 4; i++)
{
String s = reader.GetString(i);
Console.Write(s + "\t");
}
Console.Write("\n");
}
Console.ReadLine();
conn.Close();
}
}
}

can any one help me how to connect database in oracle and the connection string in c#

protected void Page_Load(object sender, EventArgs e)
{
OracleConnection con = new OracleConnection();
con.ConnectionString = "User id =test;password=test1;Datasource=oracle";
myConnection.Open();
}
Above is the code that I am using. It will be called on page_Load.
Follow below steps,below is my sample example:
1.In Web.config of your file add below string
<connectionStrings>
<add name="CustomerDataConnectionString" connectionString="Data Source=.;User Id=*;Password=*;Integrated Security=SSPI;Initial Catalog=Northwind;OLEDB.NET=True" providerName="Oracle.DataAccess.Client"/>
</connectionStrings>
//* must be filled with your credentials
2.Now in the code behind file,Import namespace for oracle client and Configuration manager for oracle client and below code
using System.Data.OracleClient;
using System.Data;
using System.Configuration;
3.Write below code in your Page_Load event:Cmd can be SQL command
static string strConnectionString = ConfigurationManager.ConnectionStrings["CustomerDataConnectionString"].ConnectionString;
using (OracleConnection con = new OracleConnection(strConnectionString))
{
try
{
if (con.State != ConnectionState.Open)
{
con.Open();
}
using (OracleDataAdapter da = new OracleDataAdapter(cmd))
{
table = new DataTable();
da.Fill(table);
}
}
catch (Exception ex)
{
throw ex;
}
}
}
Refer this link http://www.connectionstrings.com/ for more inforamtion
string oradb = "User id =test;password=test1;Datasource=oracle";
OracleConnection conn = new OracleConnection(oradb);
conn.Open();
using (OracleDataAdapter a = new OracleDataAdapter(
"SELECT id FROM emp1", conn))
{
DataTable t = new DataTable();
a.Fill(t);
// Render data onto the screen
dataGridView1.DataSource = t;
}
conn.Dispose();
Make sure you have included the required libraries,
try using this code ,
MySql.Data.MySqlClient.MySqlConnection conn;
string myConnectionString;
myConnectionString = "server=127.0.0.1;uid=root;" +
"pwd=12345;database=test;";
try
{
conn = new MySql.Data.MySqlClient.MySqlConnection();
conn.ConnectionString = myConnectionString;
conn.Open();
}
catch (MySql.Data.MySqlClient.MySqlException ex)
{
MessageBox.Show(ex.Message);
}
It's always better to have try-catch. that helps you track the exact error if you are stuck somewhere.

ASP.net newline is constante

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;

How to retrieve column value of sql server table and store it in label.Text of c# ASP.Net

My question is
Suppose I have a Column "fname" whose value is 'Nikhil' in table "profile".
How to retrieve column value of sql server table and store it in label.Text of c# ASP.Net.
I mean what should be the code if I want label text to be "fname" value that is "Nikhil"
Connection is already done properly because I am able to display table data in Gridview.
label1.Text = ?; // I want fname here
Regards,
Nikhil
Go to MSDN to learn it http://msdn.microsoft.com/en-us/bb188199.
Here's a sample on how to connect to a database.
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();
// Call Read before accessing data.
while (reader.Read())
{
Console.WriteLine(String.Format("{0}, {1}",
reader[0], reader[1]));
}
// Call Close when done reading.
reader.Close();
}
}
There are many resources out there, try to search first before posting question.
Firstly, I established a connection
SqlConnection con = new SqlConnection("data source=.\\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true");
SqlCommand cmd = new SqlCommand();
and then,
cmd.CommandText = "select fname from table where qid=1";
cmd.Connection = con;
string fname = ((string)cmd.ExecuteScalar());
or
Label1.text = ((string)cmd.ExecuteScalar());
First Create A connection Class in App_code folder and dont forget to set database path
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
/// <summary>
/// Summary description for Connection
/// </summary>
public class Connection
{
SqlConnection con = new SqlConnection();
SqlDataAdapter ad;
SqlCommand cmd;
SqlDataReader rd;
public Connection()
{
// Set Your Database Path Here from C:\user onwords
con.ConnectionString = #"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\SIROI.COM\Documents\Visual Studio 2008\WebSites\WebSite14\App_Data\ASPNETDB.MDF;Integrated Security=True;User Instance=True";
}
public DataSet filldata(DataSet ds, string query, string tbname)
{
try
{
con.Open();
ad = new SqlDataAdapter(query, con);
ad.Fill(ds, tbname);
}
catch (SqlException ex)
{
}
finally
{
con.Close();
}
return ds;
}
public bool ExecuteQuery(string query)
{
bool flag = false;
try
{
con.Open();
cmd = new SqlCommand(query, con);
int a = cmd.ExecuteNonQuery();
if (a > 0)
{
flag = true;
}
}
catch(Exception ex)
{
}
finally
{
con.Close();
}
return flag;
}
public SqlDataReader ExecuteReader(string query)
{
try
{
con.Open();
cmd = new SqlCommand(query, con);
rd = cmd.ExecuteReader();
}
catch (Exception ex)
{
}
return rd;
}
}
Now create data source by calling connection
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:ASPNETDBConnectionString1 %>"
SelectCommand="Your * SQL Query">
<SelectParameters>
<asp:QueryStringParameter Name="Your param" QueryStringField="Your Field"
Type="String" />
</SelectParameters>
</asp:SqlDataSource>
Now at last
Create a Label and set field name to retrive in Bind Function
<asp:Label ID="Label6" runat="server" Text='<%# Bind("your Field") %>'></asp:Label>
Regards http://www.siroi.com Dont Forget to like us on Facebook
http://www.facebook.com/siroi.india

the perfect way to connect to database?

public class SqlHelper
{
public SqlHelper()
{
}
public static SqlConnection GetConnection()
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = #"Data Source=.\SQLEXPRESS;AttachDbFilename=" + System.Web.HttpContext.Current.Server.MapPath(#"~\App_Data\learn.mdf") + ";Integrated Security=True;User Instance=True";
return conn;
}
public static SqlDataReader ExecuteReader(string sql)
{
SqlConnection con = GetConnection();
con.Open();
SqlCommand cmd = new SqlCommand(sql, con);
SqlDataReader dr = null;
try
{
dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
}
catch
{
con.Close();
return null;
}
return dr;
}
public static Object ExecuteScalar(string sql)
{
SqlConnection con = GetConnection();
con.Open();
SqlCommand cmd = new SqlCommand(sql, con);
Object val = null;
try
{
val = cmd.ExecuteScalar();
}
catch
{
con.Close();
return null;
}
finally
{
con.Close();
}
return val;
}
public static DataSet ExecuteDataSet(string sql)
{
SqlConnection con = GetConnection();
SqlCommand cmd = new SqlCommand(sql, con);
DataSet ds = new DataSet();
SqlDataAdapter adapt = new SqlDataAdapter(cmd);
try
{
adapt.Fill(ds);
}
catch
{
con.Close();
}
return ds;
}
public static void ExecuteNonQuery(string sql)
{
SqlConnection con = GetConnection();
con.Open();
SqlCommand cmd = new SqlCommand(sql, con);
try
{
cmd.ExecuteNonQuery();
}
finally
{
con.Close();
}
}
}
This is the Class which I use to implement every access to my database . But I think that the way I do connection with the database is a little bit overblown cause I have to hit the Connect function every time I need something . As well as other users going to do the same which kills the performance.
So what is the perfect way to connect with the database - and to stay connected if that better . Note that I use the database in many pages!
Thanks
First, you should be using "using" statements to ensure that all your ADO.NET objects are properly disposed of in the event of a failure:
public static void ExecuteNonQuery(string sql)
{
using(var con = GetConnection())
{
con.Open();
using(var cmd = new SqlCommand(sql, con))
{
cmd.ExecuteNonQuery();
}
}
}
However, having said that, I don't really see a problem with this approach. The advantage is that the connections, commands, adapters and whatnot are properly disposed of every time you execute a bit of SQL. If you were to make a single static SqlConnection instance, you'd escalate the chances that the connection is already in use (when, for example, iterating over the contents of a SqlDataReader).
If you are really concerned about it, provide overloads that take a connection as an extra parameter:
public static void ExecuteNonQuery(string sql, SqlConnection connection)
{
using(var cmd = new SqlCommand(sql, con))
{
cmd.ExecuteNonQuery();
}
}
This way, callers can either execute a bit of SQL that doesn't require multiple calls, or they can call your GetConnectionMethod to obtain a connection, and pass it to multiple calls.
If this is used for a web site then you have to consider that between requests for pages, even from the same browser, your server state will be torn down (in general terms) so there's nothing really to be gained from trying to maintain your SQL connection between pages. That's the first thing.
If each page is the result of a single database connection then you are probably as optimised as you really need to be, if you are making several connections over the generation of a page then you may want to look at keeping a connection alive until you have finished retrieving data; either by maintaining the connection or optimising your data retrieval to limit the back and forth between your app and the db.
Maintaining a database connection is the job of the connection pool, and not the connection consumer. The best practice is to aquire a connection as late as possible and release it as soon as possible.
using(var connection = new SqlConnection(YourConnectionStringHelperFunction())
{
}
One thing that YOu might take into consideration is the Dependency Injection PAttern and some IoC controller. If every page needs to have this connection make this an injectable property (constructor probably wont work unless You implement some kind of infrastructure classes like Request) use some container (Unity, Castle, StructureMap) pack the needed things up (maybe cache, maybe some other things) and let the container do the magic (by magic I mean tons of boilerplate code) for You.
luke
First you can write a seperate class like this :
Get method for getting data (with a Select query) and Set method for manipulating data (Insert, Update, Delete)
using System.Data;
using System.Data.Odbc;
using System.Data.SqlClient; //using this you can replace instead odbc to sql
// Example SqlCommand, SqlDataAdapter
class DataBaseConnection
{
private OdbcConnection conn1 = new OdbcConnection(#"FILEDSN=C:/OTPub/Ot.dsn;" + "Uid=sa;" + "Pwd=otdata#123;"); //"DSN=Ot_DataODBC;" + "Uid=sa;" + "Pwd=otdata#123;"
//insert,update,delete
public int SetData(string query)
{
try
{
conn1.Open();
OdbcCommand command = new OdbcCommand(query, conn1);
int rs = command.ExecuteNonQuery();
conn1.Close();
return rs;
}
catch (Exception ex)
{
conn1.Close();
throw ex;
}
}
//select
public System.Data.DataTable GetData(string sql)
{
try
{
conn1.Open();
OdbcDataAdapter adpt = new OdbcDataAdapter(sql, conn1);
DataTable dt = new DataTable();
adpt.Fill(dt);
conn1.Close();
return dt;
}
catch (Exception ex)
{
conn1.Close();
throw ex;
}
}
}
in your form you can make object to that database connection class
DataBaseConnection db = new DataBaseConnection();
now you cal call get set with your get set method as following
string sqlSpecialHoliyday = "SELECT * FROM Holiday WHERE Date_Time='" + selectdate + "' AND IDH='50'";
DataTable dtAdditionalholily = db.GetData(sqlSpecialHoliyday);
AD you can Set Data Using Set method
string insertloginlog = "INSERT INTO Login_Log (Service_No, Machine_Name) VALUES ('" + serviceID + "','" + machiname + "')";
int ret = db.SetData(insertloginlog);
Hope This will help!

Categories