My parameterized insertion is not working in asp.net [closed] - c#

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
My code for parameterized data insertion is not working. I get the error:
'System.Data.SqlClient.SqlCommand' does not contain a definition for 'Parameter' and no extension method 'Parameter' accepting a first argument of type 'System.Data.SqlClient.SqlCommand' could be found (are you missing a using directive or an assembly reference?)
I added using System.Data.SqlClient.SqlCommand but it made no difference. Here's 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;
using System.Configuration;
public partial class add_data_ch1 : System.Web.UI.Page
{
SqlConnection con = new SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|\\qwhizz_ch1_Database.mdf;Integrated Security=True;User Instance=True");
protected void Page_Load(object sender, EventArgs e)
{
con.Open();
}
protected void btn_Click(object sender, EventArgs e)
{
SqlCommand cmd = new SqlCommand(#"insert into data_Table values (#fname, #lname, con);
cmd.Parameter.AddWithValue("#fname", fnameTextBox.Text);
cmd.Parameter.AddWithValue("#lname", lnameTextBox.Text);
cmd.ExecuteNonQuery();
con.Close();
}
}
Would appreciate if someone can show me where the code error is or what is missing. Thanks in advance.

Should be Parameters
cmd.Parameters.AddWithValue("#fname", fnameTextBox.Text);
//Add rest of Parameters here

SqlCommand cmd = new SqlCommand(#"insert into data_Table values (#fname, #lname, con);
I believe you're just missing an end parenthesis and quotation marks.
SqlCommand cmd = new SqlCommand(#"insert into data_Table values (#fname, #lname)", con);

Related

Connecting REST WebService to MySQL database [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I want to create a REST WebService which is connected to a MySQL database. But I got stuck at a point and don´t really know how to get further.
This is my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using SimpleRESTServer.Models;
using MySql.Data;
namespace SimpleRESTServer
{
public class PersonPersistance
{
private MySql.Data.MySqlClient.MySqlConnection conn;
public PersonPersistance()
{
string myConnectionString;
myConnectionString = "server=127.0.0.1;uid=Local Instance MySQL80; pwd=;database=employeedb";
try
{
conn = new MySql.Data.MySqlClient.MySqlConnection();
conn.ConnectionString = myConnectionString;
conn.Open();
}
catch (MySql.Data.MySqlClient.MySqlException ex)
{
}
}
public long savePerson(Person personToSave)
{
String sqlString = " INSERT INTO tblpersonnel (FirstName, LastName) VALUES ('"+ personToSave.FirstName + "','" + personToSave.LastName + "')";}
MySql.Data.MySqlClient.MySqlCommand cmd = new MySql.Data.MySqlClient.MySqlCommand(sqlString, conn);
cmd.ExecuteNonQuery();
long id = cmd.LastInsertedId;
return id;
}
}
So my problem is that in the savePerson function something doesn´t work. When I write 'sqlString' and 'conn' ind the MySqlCommand part, it always get underlined red. I don´t really know what´s wrong.
I listend to this guys tutorial: https://youtu.be/LpySuvYPMZQ
I hope somebody can help me.
Thanks for your help in advance!
You are closing the method at the sqlString variable. Just after the semi colon you have a closing curly braces.

Strange C# error while inserting in database [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
I have 2 forms in my program. I am using a SQL Server Compact 3.5 database file (.sdf) from C#
albums_tbl table has two columns: id, name
In form 1 when I use this code :
private void button1_Click(object sender, EventArgs e)
{
SqlCeCommand cm = new SqlCeCommand("INSERT INTO albums_tbl(album_name) VALUES (#album_name) ", cn);
cm.Parameters.AddWithValue("#album_name", textBox1.Text);
int affectedrows = cm.ExecuteNonQuery();
if (affectedrows > 0)
{
MessageBox.Show("insert shod !");
}
}
the program inserts well, but when I use the exact code in form 2 it errors this when I want to insert :
You don't open connection yet.
SqlCeConnection conn = null;
try
{
conn = new SqlCeConnection("Data Source = MyDatabase.sdf; Password ='<pwd>'");
conn.Open();
SqlCeCommand cmd = conn.CreateCommand();
cmd.CommandText = "INSERT INTO Customers ([Customer ID], [Company Name]) Values('NWIND', 'Northwind Traders')";
cmd.ExecuteNonQuery();
}
finally
{
conn.Close();
}
Refer: https://msdn.microsoft.com/en-us/library/system.data.sqlserverce.sqlceconnection(v=vs.100).aspx
Hope this helps.
You have not opened a connection , you just simply need to do as follow
private void button1_Click(object sender, EventArgs e)
{
SqlCeConnection con=new SqlCnConnection("Data Source = MyDatabase.sdf; Password ='<pwd>'");
SqlCeCommand cm = new SqlCeCommand("INSERT INTO albums_tbl(album_name) VALUES (#album_name) ", cn);
cm.Parameters.Add(new SqlCeParameter(#album_name, textBox1.Text));
con.Open();
cm.ExecuteNonQuery();
}

"Incorrect syntax" error when running SQL query [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
I am trying to insert into database using this class, I am able to access this class in My Customer page, but getting error
Incorrect syntax near '#ZipCode'.
Meanwhile I don't have any stored procedure or trigger in my SQL Server database.
public class CustomerDLL
{
SqlConnection cn;
SqlCommand cmd;
SqlDataAdapter da;
DataSet ds;
public CustomerDLL()
{
cn = new SqlConnection(ConfigurationManager.ConnectionStrings["conn"].ConnectionString);
}
public void Insert_Customer(string name, string address, string city, string state, int ZipCode)
{
cmd = new SqlCommand("Insert into Customer values (#name, #address, #city, #state, #ZipCode", cn);
cmd.Parameters.AddWithValue("#name", name);
cmd.Parameters.AddWithValue("#address", address);
cmd.Parameters.AddWithValue("#city", city);
cmd.Parameters.AddWithValue("#state", state);
cmd.Parameters.AddWithValue("#ZipCode", Convert.ToInt32(ZipCode) ); // Line 34
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
}
}
I am accessing this class in Customer page using this method
protected void btnAdd_Click(object sender, EventArgs e)
{
// Create an instance of CustomerDll
CustomerDLL cusdll = new CustomerDLL();
//int zip = Convert.ToInt32(txtZip.Text);
cusdll.Insert_Customer
(
txtName.Text,
txtAddress.Text,
txtCity.Text,
txtState.Text,
Convert.ToInt32(txtZip.Text)
);
lblMsg.Text = "Rec is inserted successfully";
cusdll = null;
}
I keep getting error
Incorrect syntax near '#ZipCode' on line 34.
I think you missed closing parenthesis after #ZipCode.

Visual Studio SqlException was unhandled: Login failed for user 'sa' [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I have a very simple Windows Form. I want to add data to a database by using it.
In my C# winforms solution, I created a data source named db_studentDataSet and connected my database db_student. Whenever I run my solution, I get the following exception:
SqlException was unhandled: Login failed for user 'sa'
Here's my code:
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace SimpleEnrollmentSystem
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void buttonAdd_Click(object sender, EventArgs e)
{
this.Validate();
this.studentsBindingSource.EndEdit();
studentsTableAdapter.Insert("Ahmed", "Rownak", "Male", 13, "Malibagh");
}
}
}
Here's a image of my form:
Here's my database:
CREATE TABLE Students
(
StudentID int primary key,
FirstName string,
LastName string,
Gender string,
Age int,
Address string
)
Note that I've only coded for the Add button functionality.
What is wrong with my code? Or is it anything else? Maybe the way I'm trying to achieve this is wrong? Is there a better way, in that case?
I'm using Visual Studio 2012 Ultimate and SQL Server 2012 Express Edition.
EDIT - 1: I have changed my buttonAdd_Click() method.
private void buttonAdd_Click(object sender, EventArgs e)
{
SqlConnection con1 = new SqlConnection("Data Source=SAADMAAN;Initial Catalog=db_student;User ID=sa;Password=***********");
con1.Open();
SqlCommand cmd1 = new SqlCommand("INSERT INTO Students(StudentID, FirstName, LastName, Gender, Age, Address) VALUES('" + studentIDTextBox.Text + "','" + firstNameTextBox.Text + "','" + lastNameTextBox.Text + "','" + genderTextBox.Text + "','" + ageTextBox.Text + "','" + addressTextBox.Text +"')",con1);
cmd1.ExecuteNonQuery();
con1.Close();
}
According to user Kiran Hegde's suggestion, I changed the password into clear text in my connection string.
SqlConnection con1 = new SqlConnection("Data Source=SAADMAAN;Initial Catalog=db_student;User ID=sa;Password=open");
That solved the problem. So silly of me, I skipped this obvious thing.

Data Input asp.net C# SQL

Hey guys I am using a connection string database set-up inside visual studios 2012.
I am trying to send data to the database there are no errors in the code but its not running, any help would be fantastic as i have been at it for a few hours now and need some sleep.
Thanks.
Default page 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;
using System.Data;
namespace WebApplication1
{
public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection cs = new SqlConnection("Data Source = (LocalDB)\v11.0; Initial Catalog = Database1; Integrated Security = true");
SqlDataAdapter da = new SqlDataAdapter();
da.InsertCommand = new SqlCommand("INSERT INTO Adopter (FIRSTNAME,LASTNAME) VALUES (#FIRSTNAME,#LASTNAME)", cs);
da.InsertCommand.Parameters.Add("#FIRSTNAME", SqlDbType.VarChar).Value = firstname.Text;
da.InsertCommand.Parameters.Add("#LASTNAME", SqlDbType.VarChar).Value = lastname.Text;
cs.Open();
da.InsertCommand.ExecuteNonQuery();
cs.Close();
}
protected void firstname_TextChanged(object sender, EventArgs e)
{
}
protected void lastname_TextChanged(object sender, EventArgs e)
{
}
}
}
SQL code
CREATE TABLE [dbo].[Adopter] (
[FIRSTNAME] VARCHAR (50) NOT NULL,
[LASTNAME] VARCHAR (50) NOT NULL,
);
I know it will be something simple... I just cant see it.
So, as we discussed in comments, it looks like the issue you have is with your connection string. You have:
SqlConnection cs = new SqlConnection("Data Source = (LocalDB)\v11.0;
Initial Catalog = Database1; Integrated Security = true");
What you need is:
SqlConnection cs = new SqlConnection("Data Source = .\SqlInstanceName;
Initial Catalog = Database1; Integrated Security = true");
The data source is the instance on your local machine, a hosted database or some other flavor of a Sql instance and the 'Initial Catalog' is the actual database name.
PS - I highly recommend that you look into the using keyword and wrap your command and connection objects with it so that when they fall out-of-scope, they are managed for you. It looks a bit like this when you use them:
using (SqlConnection cs = new SqlConnection())
{
// Some code can go here.
using (SqlCommand cmd = new SqlCommand())
{
// More code can go here.
}
}
I have a more comprehensive answer about it on this post. Happy coding!

Categories

Resources