I am trying to create a simple website in VS Express for Web 2013 which can interact with a database "Parts." My database is stored in the app_data folder. I am able to view the connection in the Server Explorer, which implies the connection string is saved. However, the following code throws 2 errors:
Error 13 The best overloaded method match for 'System.Data.SqlClient.SqlCommand.SqlCommand(string, System.Data.SqlClient.SqlConnection)' has some invalid arguments
Error 14 Argument 2: cannot convert from 'string' to 'System.Data.SqlClient.SqlConnection'
I don't know how to remedy this. Here is my c# code:
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class _Default : System.Web.UI.Page
{
protected void insertButton_Click(object sender, EventArgs e)
{
string connstring = System.Configuration.ConfigurationManager.ConnectionStrings["connect"].ConnectionString;
SqlCommand cmd = new SqlCommand("INSERT INTO PARTS VALUES('" + nameBox.Text + "', '" + descriptionBox.Text + "', '" + quantityBox.Text + "', '" + categoryList.SelectedValue + "')", connstring);
cmd.ExecuteNonQuery();
}
}
I'm completely new to c#, so please keep that in mind. Thanks for your help.
UPDATE: The following code throws two errors, both of which are:
Error 15 The name 'conn' does not exist in the current context
I'm new to c#, but it doesn't look like there's anything wrong with the code. The name "conn" is clearly defined right above.
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class _Default : System.Web.UI.Page
{
protected void insertButton_Click(object sender, EventArgs e)
{
using (var conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["connect"].ConnectionString))
using (var cmd = new SqlCommand(
"INSERT INTO PARTS VALUES(#name, #description, #quantity, #category)", conn))
{
cmd.Parameters.AddWithValue("name", nameBox.Text);
cmd.Parameters.AddWithValue("description", descriptionBox.Text);
cmd.Parameters.AddWithValue("quantity", quantityBox.Text);
cmd.Parameters.AddWithValue("category", categoryList.SelectedValue);
conn.Open();
cmd.ExecuteNonQuery();
}
}
}
using(var conn = new SqlConnection(connectionString))
{
conn.Open();
// use conn to create the command
}
But important: YOUR SQL IS REALLY REALLY DANGEROUS. That is open to SQL injection, a HUGE and trivially easy attack surface. Please please parameterize that.
For example:
using(var conn = new SqlConnection(connectionString))
using(var cmd = new SqlCommand(
"INSERT INTO PARTS VALUES(#name, #description, ...)", conn))
{
cmd.Parameters.AddWithValue("name", nameBox.Text);
cmd.Parameters.AddWithValue("description", descriptionBox.Text);
//...
conn.Open();
cmd.ExecuteNonQuery();
}
(note you need to add a few yourself; I have left it incomplete, just name and description used for example)
What is connect value from your config?
Can you try
SqlConnection conn = new SqlConnection(connstring);
conn.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
and now issue the query.
You need to create a SqlConnection first:
string connstring = System.Configuration.ConfigurationManager.ConnectionStrings["connect"].ConnectionString;
SqlConnection conn = new SqlConnection(connstring);
SqlCommand cmd = new SqlCommand("INSERT INTO PARTS VALUES('" + nameBox.Text + "', '" + descriptionBox.Text + "', '" + quantityBox.Text + "', '" + categoryList.SelectedValue + "')"
, conn);
cmd.ExecuteNonQuery();
Some early habits to get into:
Do not concatenate SQL strings. This is for several reasons, not the least of which is the vulnerability to SQL Injection attacks.
wrap your connection and command in using statements. That ensures that the connections are closed properly if there is an exception.
The end result will look something like:
string connstring = ConfigurationManager.ConnectionStrings["connect"].ConnectionString;
using(SqlConnection conn = new SqlConnection(connstring))
{
string sql = "INSERT INTO PARTS VALUES(#name, #description, #quantity, #categoryList)"
using(SqlCommand cmd = new SqlCommand(sql , conn))
{
cmd.Parameters.AddWithValue("#name", nameBox.Text);
... etc.
cmd.ExecuteNonQuery();
}
}
Related
I know this title seems to be repeated a lot but I tried to search and didn't find the answer.
Code:
using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e) {}
protected void gv_master_SelectedIndexChanged(object sender, EventArgs e)
{
// Get the currently selected row using the SelectedRow property.
GridViewRow row = gv_master.SelectedRow;
// Display the first name from the selected row.
// In this example, the third column (index 2) contains
// the first name.
lbl_reqNoV.Text = row.Cells[1].Text;
lbl_reqNoV.Visible = true;
lbl_reqNo.Visible = true;
SqlConnection sqlConnection1 = new SqlConnection("Data Source=saitest01;Initial Catalog=SAI_website;Persist Security Info=True;User ID=sa;Password=sai#987");
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "Select * from purchase Where ReqNo = '" + lbl_reqNoV.Text + "', sqlConnection1";
cmd.CommandType = CommandType.Text;
cmd.Connection = sqlConnection1;
sqlConnection1.Open();
SqlDataReader DR1;
DR1 = cmd.ExecuteReader();
DR1.Read();
// Data is accessible through the DataDR1 object here
gv_full.DataSource = DR1;
gv_full.DataBind();
}
}
the problem is you where adding the name of Connection in the query text which is ofcource not recognized by sqlserver the correct format was
var cmd = new SqlCommand("Select * from purchase Where ReqNo = #reqno",sqlConnection1)
or you can do this
cmd.CommandText = "Select * from purchase Where ReqNo = #reqno";
cmd.Parameters.AddWithValue("reqno",lbl_reqNoV.Text);
cmd.CommandType = CommandType.Text;
cmd.Connection = sqlConnection1;
you should always use parameters in query to avoid Sql Injection
just change following
cmd.CommandText = "Select * from purchase Where ReqNo = '" + lbl_reqNoV.Text + "', sqlConnection1";
with,
cmd.CommandText = "Select * from purchase Where ReqNo = '" + lbl_reqNoV.Text + "' ";
Above will make your code working. But you should modify you code to handle SQL Injection. As answered by #Usman
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();
}
}
}
I have a Form where I am inserting a record into the database. There are two tables, table_1 is called members, and table_2 is called Amount.
I am using two SQL INSERT statements to send records to database , because that’s the way I have figured out -- there might be other ways, which I don’t know.
When I insert the record I get a message that it is inserted successfully, but when I check the database the inserted record replaces the one present , so I have last record in the DB repeated several times. Please assist.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace CemiyetAidatSistem
{
public partial class AddMember : Form
{
public AddMember()
{
InitializeComponent();
}
SqlConnection con = new SqlConnection("Data Source=My-PC\\SQLSERVER;Initial Catalog=FredericiaDernek;Integrated Security=True");
private void btnInsert_Click(object sender, EventArgs e)
{
SqlCommand cmd = new SqlCommand();
string Sql = "INSERT INTO Uyeleri ( dID, FullName, Address, Mobile, Email, Comments ) VALUES ('" + txtdID.Text + "', '" + txtAdiSoyadi.Text + "','" + txtAddress.Text + "','" + txtMobile.Text + "','" + txtEmail.Text + "','" + txtComments.Text + "')";
cmd.CommandText = Sql;
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
Sql = "INSERT INTO Aidat (dID Year, Amount ) VALUES ('"+ txtdID.Text +"','" + txtYear.Text + "','" + txtAmount.Text + "')";
cmd.CommandText = Sql;
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
for (int i = 0; i < this.Controls.Count; i++)
{
if (this.Controls[i] is TextBox)
{
this.Controls[i].Text = "";
}
}
MessageBox.Show("Data Added Scuessfully");
}
}
}
I have rewritten your code to correct errors and bad practices
string connString = "Data Source=My-PC\\SQLSERVER;Initial Catalog=FredericiaDernek;Integrated Security=True";
private void btnInsert_Click(object sender, EventArgs e)
{
using(SqlConnection con = new SqlConnection(connString))
{
con.Open();
string Sql = "INSERT INTO Uyeleri (dID, FullName, Address, Mobile, Email, Comments ) " +
"VALUES (#id, #name, #address, #mobile, #email, #comments");
using(SqlCommand cmd = new SqlCommand(Sql, con))
{
cmd.Parameters.AddWithValue("#id", txtdID.Text);
cmd.Parameters.AddWithValue("#name", txtAdiSoyadi.Text);
cmd.Parameters.AddWithValue("#address", txtAddress.Text);
cmd.Parameters.AddWithValue("#mobile", txtMobile.Text);
cmd.Parameters.AddWithValue("#email", txtEmail.Text);
cmd.Parameters.AddWithValue("#comments", txtComments.Text);
cmd.ExecuteNonQuery();
Sql = "INSERT INTO Aidat (dID, [Year], Amount ) VALUES " +
"(#id, #year, #amount)";
cmd.Parameters.Clear();
cmd.CommandText = Sql; // <- missing this in the previous version.....
cmd.Parameters.AddWithValue("#id", txtdID.Text);
cmd.Parameters.AddWithValue("#name", txtYear.Text);
cmd.Parameters.AddWithValue("#amount", txtAmount.Text);
cmd.ExecuteNonQuery();
}
}
What I have changed:
The second insert statement is wrong. Missing a comma between first
and second column
Removed the creation of the SqlConnection at the global level
Added appropriate using statement to dispose the SqlConnection and
SqlCommand also in case of exceptions
Used parameters for the two insert statements
Added square brackets around Year field (Year is a reserved keyword
in T-SQL)
Creating a SqlConnection at the global level is bad, because you grab system resources and you don't dispose them for the lifetime of your application. And the situation could be out of control in case of exceptions not correctly handled.
Now I have some doubt about your tables. The fields dID (both tables) and Amount are of text type (varchar,nvarchar)?. If they are of numeric type it is necessary to add a conversion before adding the values to the Parameters collection
I would also suggest changing your for loop to clear the controls replace this
for (int i = 0; i < this.Controls.Count; i++)
{
if (this.Controls[i] is TextBox)
{
this.Controls[i].Text = "";
}
}
with the following code using linq.
this.Controls.OfType<TextBox>().ToList().ForEach(textBox => textBox.Clear());
keep in mind that 'this' will refer to the name of your Form
so it would be
(YourWinFormsName).Controls.OfType<TextBox>().ToList().ForEach(textBox => textBox.Clear());
net to adding database. I am trying to do texts on two textbox and one selected value in dropdownlist to add my table.
Here is my code
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;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
string connectionString = #" Data Source=.\SQLEXPRESS;AttachDbFilename=C:\USERS\CEM\DOCUMENTS\VISUAL STUDIO 2010\WEBSITES\EKLEMEDENE\APP_DATA\DATABASE.MDF;Integrated Security=True;User Instance=True";
string queryString = "INSERT INTO ekle(flight, name, food) VALUES ('" + TextBox1.Text + " ' , '" + TextBox2.Text + " ' , '" + DropDownList1.SelectedValue + " ' )";
SqlConnection con = new SqlConnection(connectionString);
SqlCommand command = new SqlCommand(queryString, con);
con.Open();
command.ExecuteNonQuery();
con.Close();
}
}
After I execute I will have error
Database 'C:\Users\Cem\Documents\Visual Studio 2010\WebSites\eklemedene\App_Data\Database.mdf' already exists. Choose a different database name.
An attempt to attach an auto-named database for file C:\USERS\CEM\DOCUMENTS\VISUAL STUDIO 2010\WEBSITES\EKLEMEDENE\APP_DATA\DATABASE.MDF failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share.
You're wide open for SQL-Injection. Avoid passing parameters directly from controls. Instead use Parameters.
Use using-statement for anything implementing IDisposable like Connections or Commands:
There's something wrong with your ConnectionString, you could try to use SqlConnectionStringBuilder class:
//Build the connection
SqlConnectionStringBuilder bldr = new SqlConnectionStringBuilder();
//Put your server or server\instance name here. Likely YourComputerName\SQLExpress
bldr.DataSource = ".\\SQLEXPRESS";
//Attach DB Filename
bldr.AttachDBFilename = #"C:\USERS\CEM\DOCUMENTS\VISUAL STUDIO 2010\WEBSITES\EKLEMEDENE\APP_DATA\DATABASE.MDF";
//User Instance
bldr.UserInstance = true;
//Whether or not a password is required.
bldr.IntegratedSecurity = true;
using(var connection = new SqlConnection(bldr.ConnectionString))
{
var sql = "INSERT INTO ekle(flight, name, food) VALUES (#flight, #name , #food)";
using(var command = new SqlCommand(sql, connection))
{
command.Parameters.AddWithValue("#flight", TextBox1.Text);
command.Parameters.AddWithValue("#name", TextBox2.Text);
command.Parameters.AddWithValue("#food", DropDownList1.SelectedValue);
connection.Open();
command.ExecuteNonQuery();
}
} // closes the connection implicitely
how are you,sir my code is correct means there is no error after debugging that code.My goal is that if the user click on button(which is placed in default.aspx,for example)then the database table is created in database(database placed within sql express),I write the code for that purpose we debug the code and there is no error in the code .when i click the button(in runtime).when i check the database(which is in the sql express)there is no table is created in that database.please sir solve my problem.The code written in c# behind the button is that:
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
//using PractiseWeb.DataSet1TableAdapters;
using System.Collections.Generic;
using System.Data.OleDb;
using System.Diagnostics;
using System.ComponentModel;
using System.Text;
using System.Data.SqlClient;
using System.Data.Odbc;
using ADOX;
using ADODB;
public partial class _Default : System.Web.UI.Page
{
SqlConnection conn;
SqlCommand cmd;
string connectionString = ConfigurationManager.ConnectionStrings["gameConnectionString"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
try
{
conn = new SqlConnection(connectionString);
if (!(conn.State == ConnectionState.Open))
{
conn.Open();
}
string sql = "CREATE TABLE mySchoolRecord(StudentId INTEGER CONSTRAINT PkeyMyId PRIMARY KEY, Name CHAR(50)," + "Address CHAR(255)," + "Contact INTEGER));";
cmd = new SqlCommand(sql, conn);
cmd.ExecuteNonQuery();
sql = "INSERT INTO mySchoolRecord (StudentId, Name,Address,Contact) VALUES (1, 'Mr. Manish', " + " 'Sector-12,Noida', 2447658 );";
cmd = new SqlCommand(sql, conn);
cmd.ExecuteNonQuery();
sql = "INSERT INTO mySchoolRecord (StudentId, Name,Address,Contact) VALUES (2, 'Mr. Ravi', " + " 'New Delhi', 2584076521 );";
cmd = new SqlCommand(sql, conn);
cmd.ExecuteNonQuery();
sql = "INSERT INTO mySchoolRecord (StudentId, Name,Address,Contact) VALUES (3, 'Mr. Peter', " + " 'United States', 25684124 );";
cmd = new SqlCommand(sql, conn);
cmd.ExecuteNonQuery();
if (conn.State == ConnectionState.Open)
{
conn.Close();
}
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
}
THANKS SIR
Remove the try-catch and see what's happening. Writing to the console isn't going to help much in an ASP.NET app. :)
using System;
using System.Data;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
SqlConnection conn;
SqlCommand cmd;
string connectionString = ConfigurationManager.ConnectionStrings["gameConnectionString"].ConnectionString;
protected void Button1_Click(object sender, EventArgs e)
{
using (conn = new SqlConnection(connectionString))
{
if (!(conn.State == ConnectionState.Open))
{
conn.Open();
}
string sql = "CREATE TABLE mySchoolRecord(StudentId INTEGER CONSTRAINT PkeyMyId PRIMARY KEY, Name CHAR(50)," + "Address CHAR(255)," + "Contact INTEGER));";
cmd = new SqlCommand(sql, conn);
cmd.ExecuteNonQuery();
sql = "INSERT INTO mySchoolRecord (StudentId, Name,Address,Contact) VALUES (1, 'Mr. Manish', " + " 'Sector-12,Noida', 2447658 );";
cmd = new SqlCommand(sql, conn);
cmd.ExecuteNonQuery();
sql = "INSERT INTO mySchoolRecord (StudentId, Name,Address,Contact) VALUES (2, 'Mr. Ravi', " + " 'New Delhi', 2584076521 );";
cmd = new SqlCommand(sql, conn);
cmd.ExecuteNonQuery();
sql = "INSERT INTO mySchoolRecord (StudentId, Name,Address,Contact) VALUES (3, 'Mr. Peter', " + " 'United States', 25684124 );";
cmd = new SqlCommand(sql, conn);
cmd.ExecuteNonQuery();
if (conn.State == ConnectionState.Open)
{
conn.Close();
}
}
}
}
#sayyer ,
follow the below steps
1)can you copy your sql and paste on sqlserver directly and see if it creating or not?? do a break on exception while debuggin ,it will tell you if there are any exceptions in the code
2) Check your database connection
3) check all the formating for the insert statements.
Best way to fix the issue is do ctr + alt + E and check break on exceptions, that will fix your problem
Try removing semicolons from SQL queries.