SqlCommand Method Error while executing INSERT query in WPF Application - c#

I am working on WPF application in C#. Database is SQL Server 2008. I have a table "Employee" in database, I need to insert a row in it. I have successfully connected with database, but when I tried to execute this line:
cmd = new SqlCommand(cmdText, conn);
This errors comes up: The best overloaded method match for 'System.Data.SqlClient.SqlCommand.SqlCommand(String, System.Data.SqlClient.SqlConnection)' has some invalid arguments.
Here is my code:
private void addbtn_Click(object sender, RoutedEventArgs e)
{
//FUNCTION TO ADD NEW EMPLOYEE RECORD IN DATABASE
try
{
conn.ConnectionString = "Data Source=AZEEMPC;" + "Initial Catalog=IEPL_Attendance_DB;";
conn.Open();
cmdText = "INSERT INTO Employee VALUES ('" + strCurrentString + "','" + emp_name.Text + "')";
cmd = new SqlCommand(cmdText, conn);
data_ad = new SqlDataAdapter(cmd);
data = new DataSet();
data_ad.Fill(data);
MessageBox.Show("Record Inserted Successfully!");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Any suggestions?

conn needs to be of type SqlConnection - can you confirm that it is?
SqlConnection conn;
Because it's a native SQL Server connection, you don't need to pass the driver name in the connection string.
conn.ConnectionString = "Server=AZEEMPC;Database=IEPL_Attendance_DB;Trusted_Connection=true;";

Related

Visual Studio Login Page with local SQL server database

I'm creating a visual studio project that uses a local SQL server database as a data source, which is up and running correctly.
I need to create a login form for the project.
The form has a username textbox and a password textbox which the user will populate with their details, and then hit the 'login' button, which needs to execute the select sql statement.
Any references on how to do this?
The code I have tried is below.
It's throwing a NullReferenceException at the line that says "SqlDataReader dr = cmd.ExecuteReader();"
How do I Solve the nullreferenceexception?
Thank you!
private void button1_Click(object sender, EventArgs e)
{
try
{
SqlConnection con = new SqlConnection();
con.ConnectionString = "Data Source=MARKO-PC\\SQLEXPRESS;Initial Catalog=IS2B_G8_FundMeDB;Integrated Security=True";
con.Open();
String sql = "Select * from APPLICANT where applicant_ID_passport =#user AND password = #password";
SqlCommand cmd = new SqlCommand(sql, con);
cmd.Parameters.Add(new SqlParameter("#user", txtUserName.Text));
cmd.Parameters.Add(new SqlParameter("#password", txtPassword.Text));
SqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows == true)
{
MessageBox.Show("Login Successful");
}
else
{
MessageBox.Show("Login Failed");
}
}
catch (SqlException sqle)
{
MessageBox.Show("Sql Exception");
}
}
Try this
string struser = txtUserName.Text;
string strpwd = txtPassword.Text;
String sql = "Select * from APPLICANT where applicant_ID_passport=" + struser + " AND password = " + strpwd +"";
SqlCommand cmd = new SqlCommand(sql, con);
SqlDataReader dr = cmd.ExecuteReader();
You need to do some research into using ADO.Net, specifically the SQLCommand class.
However I would refrain from using inline sql statements like above as this opens you up to SQL injection. Rather use paramaterised queries, stored procedures or LINQ to SQL.

How to execute foxpro 2.6(DOS) commands from C# that needs exclusive access to table?

This is my code, and I want to delete all the data of the FoxPro tables named as SMS_DATA, I tried ZAP command, as well as also tried DELETE ALL and PACK command with the USE -table-name, but it doesn't working, and gives the exception that:
System.Data.OleDb.OleDbException (0x80004005): File must be opened exclusively.
This is my code:
string USETBL ="EXECSCRIPT([USE SMS_DATA && Open SMS_DATA table])";
string DELETE="EXECSCRIPT([DELETE ALL])";
string PACK="EXECSCRIPT([PACK])";
OleDbConnection con = new OleDbConnection(conStr);
try
{
OleDbCommand cmd = new OleDbCommand(USETBL, con);
OleDbCommand cmd1 = new OleDbCommand(DELETE, con);
OleDbCommand cmd2 = new OleDbCommand(PACK, con);
con.Open();
err.log("connection opened");
cmd.ExecuteNonQuery();
err.log("table in use");
cmd1.ExecuteNonQuery();
err.log("delete executed.");
cmd2.ExecuteNonQuery();
err.log("pack executed.");
con.Close();
}
catch (Exception e)
{
err.log("Exception:-" + e);
}
Your first line should be:
EXECSCRIPT([USE SMS_DATA EXCLUSIVE && Open SMS_DATA table]);
for safety I would also change the next two lines to:
string DELETE="EXECSCRIPT([DELETE ALL IN SMS_DATA])";
string PACK="EXECSCRIPT([PACK IN SMS_DATA])";

C# simple code to write an INSERT query is giving an exception

I have a very basic and beginner problem. I got a 5 line code and I got exception in that.
My database :
It has one table and two columns inside the table viz. id and name.
I made a form.
Here is my code:
private void button1_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection("Data Source=(LocalDB)\\v11.0;AttachDbFilename=\"C:\\Users\\Nicki\\documents\\visual studio 2012\\Projects\\WindowsFormsApplication2\\WindowsFormsApplication2\\Database2.mdf\";Integrated Security=True");
conn.Open();
SqlCommand command = new SqlCommand("INSERT INTO Table (id,name) VALUES (1,'" + textBox1.Text + "')", conn);
command.ExecuteNonQuery();
conn.Close();
}
I get the following exception on running the code:
It says that I have syntax error even though the syntax error is correct. Any help would be appreciated.
Thankyou!
You should use a using clause to properly manage resources and use parameters to avoid security problems. It is not recommended to use reserved words as "table". Try this:
const string commandText = "INSERT INTO [Table] (id,name) VALUES (1,#Name)";
using (SqlConnection connection = new SqlConnection(ConnectionString))
{
SqlCommand command = new SqlCommand(commandText, connection);
command.Parameters.Add("#Name", SqlDbType.VarChar);
command.Parameters["#Name"].Value = textBox1.Text;
connection.Open();
var rowsAffected = command.ExecuteNonQuery();
}

SQL Server Error, 'Keyword not supported 'datasource'

I'm currently trying to INSERT some values into a datasource, then display them on another page using the DataList control. However, after some testing and experimentation, I've found that the error comes from the very beginning.
Here is the code I have bound to my button.
protected void btnSend_Click(object sender, EventArgs e)
{
Page.Validate("vld2");
SendMail();
lblMsgSend.Visible = true;
txtPhone.Text = "";
txtEmail.Text = "";
txtName.Text = "";
txtComment.Text = "";
//SQL Server Database
SqlConnection conn; //manages connection to database
SqlCommand cmd; //manages the SQL statements
string strInsert; //SQL INSERT Statement
try
{
//create a connection object
conn = new SqlConnection("DataSource=localhost\\sqlexpress;" +
"Initial Catalog=RionServer;" +
"Integrated Security=True;");
//Build the SQL INSERT Document
strInsert = "INSERT INTO CommentsAdmin (Name,Phone,Email,Comments)"
+ "VALUES(#Name,#Phone,#Email,#Comments);";
//associate the INSERT statement with the connection
cmd = new SqlCommand(strInsert, conn);
//TELL the SqlCommand WHERE to get the data from
cmd.Parameters.AddWithValue("Name", txtName);
cmd.Parameters.AddWithValue("Phone", txtPhone);
cmd.Parameters.AddWithValue("Email", txtEmail);
cmd.Parameters.AddWithValue("Comments", txtComment);
//open the connection
cmd.Connection.Open();
//run the SQL statement
cmd.ExecuteNonQuery();
//close connection
cmd.Connection.Close();
//display status message on the webpage
lblMsgSend.Text = "Thank you for the comment! Please hit the 'Return to Main Page' to return to the Main Page!";
}
catch (Exception ex)
{
lblMsgSend.Text = ex.Message;
}
}
Here is the image of my webpage and the error it displays.
Please let me know if you need additional information.
Thanks in advance.
In your connection string, it should be "Data Source", not "DataSource". Just add a space.

display information from sql db to asp.net webpage

I think what I need is simple but I can't achieve it through asp.net because I am a total beginner.
What I need is to display a field from sql db table to my webpage like this example:
Account Information
Your Name is: <Retrieve it from db>
Your Email is: <Retrieve it from db>
How should I do that ?
I already have table members.
I need to do this with c# , I am using Visual Studio Web Express 2010
First step is add the SQL Client namespace:
using System.Data.SqlClient;
DB Connection
Then we create a SqlConnection and specifying the connection string.
SqlConnection myConnection = new SqlConnection("user id=username;" +
"password=password;server=serverurl;" +
"Trusted_Connection=yes;" +
"database=database; " +
"connection timeout=30");
This is the last part of getting connected and is simply executed by the following (remember to make sure your connection has a connection string first):
try
{
myConnection.Open();
}
catch(Exception e)
{
Console.WriteLine(e.ToString());
}
SqlCommand
An SqlCommand needs at least two things to operate. A command string, and a connection. There are two ways to specify the connection, both are illustrated below:
SqlCommand myCommand = new SqlCommand("Command String", myConnection);
// - or -
myCommand.Connection = myConnection;
The connection string can also be specified both ways using the SqlCommand.CommandText property. Now lets look at our first SqlCommand. To keep it simple it will be a simple INSERT command.
SqlCommand myCommand= new SqlCommand("INSERT INTO table (Column1, Column2) " +
"Values ('string', 1)", myConnection);
// - or -
myCommand.CommandText = "INSERT INTO table (Column1, Column2) " +
"Values ('string', 1)";
SqlDataReader
Not only do you need a data reader but you need a SqlCommand. The following code demonstrates how to set up and execute a simple reader:
try
{
SqlDataReader myReader = null;
SqlCommand myCommand = new SqlCommand("select * from table",
myConnection);
myReader = myCommand.ExecuteReader();
while(myReader.Read())
{
Console.WriteLine(myReader["Column1"].ToString());
Console.WriteLine(myReader["Column2"].ToString());
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}

Categories