This is partial code which i try
SqlConnection con = new SqlConnection(#"Data Source=ANSARI-PC\;Initial Catalog=BMS;Integrated Security=True");
string tname = idc + "-InvoiceT";
string sql = "select count(*) from '"+ tname + "' ";
con.Open();
SqlCommand sda = new SqlCommand(sql, con);
SqlDataReader myreader;
myreader = sda.ExecuteReader();
int lid;
For above code im getting this error Incorrect syntax near '2-InvoiceT'
2-InvoiceT is table name in database 'idc' contain 2 as value.
Change
string sql = "select count(*) from '"+ tname + "' ";
to
string sql = "select count(*) from ["+ tname + "] ";
Related
I wrote the query for inserting data to MySQL table "Persons":
SqlConnection con = new SqlConnection();
try
{
String insert = "INSERT INTO Persons (id,Name,Surname,Address,Phone) VALUES ('" + txtId.Text + "','" + txtName.Text + "','" + txtSurname.Text + "','" + txtAddress.Text + "','" + txtPhone.Text + "')";
con.Open();
SqlCommand cmd = new SqlCommand(insert,con);
cmd.ExecuteNonQuery();
con.Close();
}
catch
{
MessageBox.Show("Id is not valid");
}
But it's not working. I have one connection for the whole database, but it's not working for a specific table. How I can create a connection between specific table to query in C#?
What is it? SqlConnection con = new SqlConnection() you need to pass a connection string which comprises DBname, username, pasword, server name ... etc; you are not passing those information anywhere then how can you expect it to connect to your database without having the information.
Pass the connection string either in constructor or using the property.
SqlConnection con = new SqlConnection(connection_string)
(OR)
SqlConnection con = new SqlConnection();
con.ConnectionString = connection_string;
There are different ways to insert data into the tables. I suggest to use parametrized sql query to keep safe from malicious occurrence.
Firstly you should have a ConnectionString something like this:
string connectionString = "Persist Security Info=False;User ID=UserName;Password=YourPassword;Server=ServerName";
And than:
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand("INSERT INTO TableName (Col1, Col2, ColN) VALUES (#Col1, #Col2, #ColN)");
cmd.CommandType = CommandType.Text;
cmd.Connection = connection;
cmd.Parameters.AddWithValue("#Col1", txtName.Text);
cmd.Parameters.AddWithValue("#Col2", txtPhone.Text);
cmd.Parameters.AddWithValue("#ColN", txtAddress.Text);
connection.Open();
cmd.ExecuteNonQuery();
}
Try this code. Please edit your credentials before trying.
Replace localhost with SQL server instance name, user id with your MySQL server instance user id, password with your MySQL server instance password and testdb with your database name. It should work fine.
string connectionString = #"server=localhost;user id=admin;password=admin;database=testdb;";
SqlConnection con = new SqlConnection(connectionString);
try
{
String insert = "INSERT INTO Persons (id,Name,Surname,Address,Phone) VALUES ('" + txtId.Text + "','" + txtName.Text + "','" + txtSurname.Text + "','" + txtAddress.Text + "','" + txtPhone.Text + "')";
con.Open();
SqlCommand cmd = new SqlCommand(insert,con);
cmd.ExecuteNonQuery();
con.Close();
}
catch
{
MessageBox.Show("Id is not valid");
}
I'm trying to use code to insert a row into the database and then immediately display that code after after a button is clicked. I'm using C#.
comm.CommandText = "INSERT INTO Store (FirstName, LastName) Values ('" + txtFirstName.Text + "', '" + txtLastName.Text + "')";
The above code works . But it won't work if I add the following code (which will work instead):
comm.CommandText = "Select FirstName, LastName from Store";
When the button is clicked, I want to insert the row (containing information that was just entered from the textbox) into the table and also display that new row into a form (set up to view the table). I'm trying to get both of the commands to work at the same time, but only the second "Command" works.
Here is what the surrounding code looks like:
protected void btnSubmit_Click(object sender, EventArgs e)
{
String testVar = txtFirstName.Text;
OleDbConnection conn = new OleDbConnection(); //where to find db
conn.ConnectionString = ConfigurationManager.ConnectionStrings["storeConnString"].ConnectionString; //long connection screen.
conn.Open();
OleDbCommand comm = conn.CreateCommand();
comm.Connection = conn;
comm.CommandText = "INSERT INTO Store (FirstName, LastName) Values ('" + txtFirstName.Text + "', '" + txtLastName.Text + "')";
comm.CommandText = "Select FirstName, LastName from Store";
OleDbDataReader reader = comm.ExecuteReader();
(I know I need to use parameters, but I'm going to do that after I figure this out.)
Thanks, Brad
Because after this two lines, your INSERT command will not assigned to your comm anymore.
comm.CommandText = "INSERT INTO Store (FirstName, LastName) Values ('" + txtFirstName.Text + "', '" + txtLastName.Text + "')";
comm.CommandText = "Select FirstName, LastName from Store";
CommandText property only have now your SELECT stament. Just execute your INSERT query with ExecuteNonQuery and after use ExecuteReader to get your SELECT statement result.
comm.CommandText = "INSERT INTO Store (FirstName, LastName) Values ('" + txtFirstName.Text + "', '" + txtLastName.Text + "')";
comm.ExecuteNonQuery();
comm.CommandText = "Select FirstName, LastName from Store";
OleDbDataReader reader = comm.ExecuteReader();
As you said, you should always use parameterized queries. This kind of string concatenations are open for SQL Injection attacks.
And use using statement to dispose your OleDbConnection, OleDbCommand and OleDbDataReader like;
using(OleDbConnection conn = new OleDbConnection(conString))
using(OleDbCommand comm = conn.CreateCommand())
{
// Execute your INSERT query here.
// Also check your INSERT is successfull or not.
// Assing your SELECT statement to your CommandText property
using(OleDbDataReader reader = comm.ExecuteReader())
{
//
}
}
i am trying to find the records based on the user input in msaccess database.
below is the code
string strProvider = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Employees.mdb";
string strSql = "SELECT * FROM tbl_employees where description like '" + txtsearch.Text.ToString() + "*'";
OleDbConnection con = new OleDbConnection(strProvider);
OleDbCommand cmd = new OleDbCommand(strSql, con);
con.Open();
cmd.CommandType = CommandType.Text;
OleDbDataReader dr = cmd.ExecuteReader();
int columnCount = dr.FieldCount;
When i ran the same query in my SQLView of msaccess i am getting records but when i ran it in VS i am not getting any records.
I think your matching should be changed:
String strSql = "SELECT * FROM tbl_employees WHERE description LIKE '" + txtsearch.Text.ToString() + "%'";
//Replaced * with %
I have a table in MS Access that contain: (FoodID, FoodName, Price).
In C# I have three text boxes (txtId, txtName, txtPrice) and a button (btnSearch).
My question is that, In C# I just type FoodID in (txtId) and then click on button Search It'll display FoodName and Price ( from table access) in txtName and txtPrice by itself. I got the source code from you but it error on (OleDbDataReader dr = cmd.ExecuteReader();) its message is "Data type mismatch in criteria expression" .
Please solve this problem for me. This is the whole source code that I got for you.
System.Data.OleDb.OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = "your connection string";
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = conn;
cmd.CommandText = "select FoodName, Price from tablename where FoodID = '" + txtId + "' ";
conn.Open();
OleDbDataReader dr = cmd.ExecuteReader();//error this line!
while(dr.Read())
{
txtName.Text = dr["FoodName"].ToString();
txtPrice.Text = dr["Price"].ToString();
}
dr.Close();
conn.Close();
I assume FoodID is int. You should remove single quotes in this case
cmd.CommandText = "select FoodName, Price from tablename where FoodID = " + txtId;
Even better - use parameters:
using (var connection = new OleDbConnection("your connection string"))
using (var command = connection.CreateCommand())
{
command.CommandText = "select FoodName, Price from tablename where FoodID = #FoodID";
command.Parameters.AddWithValue("FoodID", int.Parse(txtId.Text));
connection.Open();
var reader = command.ExecuteReader();
while (reader.Read())
{
txtName.Text = reader["FoodName"].ToString();
txtPrice.Text = reader["Price"].ToString();
}
}
I think the FoodId is of Integer type in the database but over here in the query you have passed as string so convert the string to integer.
cmd.CommandText = "select FoodName, Price from tablename where FoodID = '" + int.Parse(txtId.Text) + "' " ;
There seems to be no problem with this line of code :
OleDbDataReader dr = cmd.ExecuteReader();// correct way
I think the problem is in:
cmd.CommandText = "select FoodName, Price from tablename where FoodID = '" + txtId + "' ";
You need to use the .Text Propertie of the Textbox
cmd.CommandText = "select FoodName, Price from tablename where FoodID = '" + txtId.Text + "' ";
My SQL query isn't dropping anything into the combobox. The connection seems to be made but the while loop doesn't seem to work. Can anybody tell me what it wrong?
string sqltable = ("dbo.SLTDS_C"+id+"_table");
SqlConnection con = new SqlConnection("Data Source=" + server + ";Initial Catalog=" + database + ";Integrated Security=" + security);
con.Open();
string sqldatapull = ("select name from syscolumns where id = object_id('" + sqltable + "') order by name asc");
SqlCommand cmd = new SqlCommand(sqldatapull, con);
cmd.CommandType = CommandType.Text;
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
sqldatapull = dr[0].ToString();
comboBox1.Items.Add(sqldatapull);
}
dr.Close();
con.Close();
Correction code:
string sqldatapull = ("select name from syscolumns where id = object_id('" + sqltable + "') order by name asc");
It's because you're including dbo. as part of the table name. If you run
SELECT * FROM INFORMATION_SCHEMA.COLUMNS
You will see that the table names have no schema in the TABLE_NAME column.