I would like to add into my query name of table from my string variable tablename. Is it possible in c#? I tried something like below. But it doesn't work. As you can see i want to set the FROM #tablename on scores
public void tableInsertTest()
{
MySqlConnection conn = null;
string tablename = "scores";
try
{
conn = new MySqlConnection(cs);
conn.Open();
MySqlCommand cmd = new MySqlCommand();
cmd.Connection = conn;
cmd.CommandTimeout = 90;
cmd.CommandText = (
"INSERT INTO dailyrecords(recorddate, firstname, lastname, score ) " +
"SELECT NOW(), name, lname, score FROM #tablename " );
cmd.Prepare();
cmd.Parameters.AddWithValue("#tablename", tablename);
{
cmd.ExecuteNonQuery();
}
conn.Close();
}
finally
{
if (conn != null)
{
conn.Close();
}
}
return;
}
cmd.CommandText = ("INSERT INTO dailyrecords(recorddate, firstname, lastname, score ) " +
string.Format("SELECT NOW(), name, lname, score FROM {0} ", tablename) );
Your query is only a string and you have the value :)
Related
I want to search data in database and put it in datatable but it seem my sql command its not correct because it didnt return any data. please help. thanks in advance. below is my code please check.
protected DataTable SearchResident(String name, String ConnStr)
{
DataTable dt = new DataTable();
try
{
SqlCommand cmd;
using (SqlConnection con = new SqlConnection(ConnStr))
{
con.Open();
String SQL = "SELECT ID, LastName, FirstName, MiddleName, Gender, BirthDate, CivilStatus, " +
"Citizenship, MobileNo, Landline, PermanentAddress, Address FROM Residents " +
"WHERE FirstName LIKE '%name%' OR LastName LIKE '%name%'";
using (cmd = new SqlCommand(SQL, con))
{
using (SqlDataReader sdr = cmd.ExecuteReader())
{
dt.Load(sdr);
}
}
}
return dt;
}
catch (Exception ex)
{
throw ex;
}
}
You wrote a request to the string SQL, but you do not use it in your code. Example SQL-query:
class SQLQuery
{
public static DataSet SQLGetData(string ConnectionString, string commandString)
{
DataSet DS = new DataSet();
DataTable DT = new DataTable("Table1");
DS.Tables.Add(DT);
using (SqlConnection connection = new SqlConnection(ConnectionString))
{
try
{
connection.Open();
SqlCommand command = new SqlCommand(commandString, connection);
//command.CommandTimeout = 3000;
SqlDataReader read = command.ExecuteReader();
DS.Load(read, LoadOption.PreserveChanges, DS.Tables[0]);
}
catch (SqlException e)
{
System.Windows.Forms.MessageBox.Show(e.Message);
}
finally
{
connection.Close();
}
}
return DS;
}
}
And get data:
private DataTable SearchData (string name)
{
DataTabel dt = new DataTable();
string connStr; // connection string
string command = "SELECT ID, LastName, FirstName, MiddleName, Gender, BirthDate,"+
"CivilStatus, Citizenship, MobileNo, Landline, PermanentAddress,"+
"Address FROM Residents WHERE FirstName LIKE '" + name +
"' OR LastName LIKE '" + name + "'";
dt = SQLQuery.SQLGetData(connStr, command).Tables[0];
return dt;
}
you need a sql command, and to add name as a parameter :-
using (SqlConnection con = new SqlConnection(ConnStr))
{
con.Open();
String SQL = "SELECT ID, LastName, FirstName, MiddleName, Gender, BirthDate, CivilStatus, " +
"Citizenship, MobileNo, Landline, PermanentAddress, Address FROM Residents " +
"WHERE FirstName LIKE '%#name%' OR LastName LIKE '%#name%'";
var cmd = new SqlCommand(SQL, connection);
cmd.Parameters.Add("#name", SqlDbType.Text);
cmd.Parameters["#name"].Value = name;
using (SqlDataReader sdr = cmd.ExecuteReader())
{
dt.Load(sdr);
}
}
You can use like this :
protected DataTable SearchResident(String name, String ConnStr)
{
try
{
String SQL = "SELECT ID, LastName, FirstName, MiddleName, Gender, BirthDate, CivilStatus, " +
"Citizenship, MobileNo, Landline, PermanentAddress, Address FROM Residents " +
"WHERE FirstName LIKE '%#name%' OR LastName LIKE '%#name%'";
using (SqlConnection sqlConn = new SqlConnection(ConnStr))
using (SqlCommand cmd = new SqlCommand(SQL, sqlConn))
{
cmd.Parameters.AddWithValue("#name", name);
sqlConn.Open();
DataTable dt = new DataTable();
dt.Load(cmd.ExecuteReader());
return dt;
}
}
catch (Exception ex)
{
throw ex;
}
}
One more suggestion, you are inviting SQL injection. Please use a parameterized stored procedure.
I have database pavadinimas.mdf, which contains two tables: Vehicle and Repairs. I want to check if both tables exist in database. So, far I managed to check if one table exist, but how to check if both exist, if not create them.
Here is my code:
string tblnm = "Vehicle";
SqlConnection conn;
using (conn = new SqlConnection(connection))
{
conn.Open();
System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand();
cmd.CommandText = #"IF EXISTS(SELECT * FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME='" + tblnm + "') SELECT 1 ELSE SELECT 0"; ;
cmd.Connection = conn;
cmd.ExecuteNonQuery();
int x = Convert.ToInt32(cmd.ExecuteScalar());
conn.Close();
if (x == 2)
{
MessageBox.Show("Lentelės yra");
}
else
{
MessageBox.Show("Lenteliu nėra.Sukuriama");
}
I also have code which should create table. Here is code:
string table1 = "Repairs";
SqlConnection conn;
conn = new SqlConnection(connection);
conn.Open();
string createString = "CREATE TABLE [dbo].['" + table1 + "'](" + "[VIN] [nvarchar](50)," + "[Taisymas] [nvarchar](50)," + "[Kaina] [decimal](18, 2))";
SqlCommand sqlCmd = new SqlCommand(createString, conn);
sqlCmd.ExecuteNonQuery();
conn.Close();
But this code don't create table in my database. Then I call this method, it is saying that table already exist, but when I check tables in database it's nothing, empty...
Are you looking for something similar to:
IF EXISTS(SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME='tbl1') AND EXISTS(SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME='tbl2') SELECT 1 ELSE SELECT 0
How about using a parameter and looping through the tables?
conn.Open();
var cmd = new System.Data.SqlClient.SqlCommand(
#"SELECT count (*) FROM INFORMATION_SCHEMA.TABLES where TABLE_NAME = #TABLE_NAME",
conn);
cmd.Parameters.Add("#TABLE_NAME", SqlDbType.VarChar);
List<String> tables = new List<string>() { "Vehicles", "Repairs" };
foreach (string tableName in tables)
{
cmd.Parameters[0].Value = tableName;
int x = Convert.ToInt32(cmd.ExecuteScalar());
if (x == 0)
CreateTable(tableName, conn);
}
conn.Close();
-- EDIT --
CreateTable method was added above, and the code would look something like this. Caveat -- this is EXTREMELY brute force, but in the absence of other information, is is one way to accomplish the task, as I best understand your issue.
private void CreateTable(String TableName, System.Data.SqlClient.SqlConnection conn)
{
StringBuilder sql = new StringBuilder(#"create table [");
sql.Append(TableName);
sql.AppendLine(#"] (");
switch (TableName)
{
case "Vehicle":
sql.AppendLine("[VIN] varchar(100),");
sql.AppendLine("[Manufacturer] varchar(100),");
sql.AppendLine("[Model] varchar(100),");
sql.AppendLine("[Year] integer");
break;
case "Repair":
sql.AppendLine("[VIN] varchar(100),");
sql.AppendLine("[Correction] varchar(100),");
sql.AppendLine("[Price] decimal");
break;
}
sql.Append(")");
System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand(
sql.ToString, conn);
try
{
cmd.ExecuteNonQuery();
MessageBox.Show("Created Table " + TableName);
}
catch (Exception ex)
{
MessageBox.Show("Oops, I did it again");
}
}
Wrap it in a for loop
for(int i = 0; i < 2; i++){
if (i = 0)
{
string tblnm = "Vehicle";
}
else
{
string tblnm = "Repairs";
}
SqlConnection conn;
using (conn = new SqlConnection(connection))
{
conn.Open();
System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand();
cmd.CommandText = #"IF EXISTS(SELECT * FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME='" + tblnm + "') SELECT 1 ELSE SELECT 0"; ;
cmd.Connection = conn;
cmd.ExecuteNonQuery();
int x = Convert.ToInt32(cmd.ExecuteScalar());
conn.Close();
if (x == 2)
{
MessageBox.Show("Lentelės yra");
}
else
{
MessageBox.Show("Lenteliu nėra.Sukuriama");
}
}
The search text box is not returning a valid person datatable on the screen, anyone have any idea why?
Database class:
static public DataTable SearchButton(string search)
{
using (var conn = new SqlConnection(DatabaseConnectionString))
{
var dt = new DataTable();
const string searchQuery = "exec SearchTerm";
using (var cmd = new SqlCommand(searchQuery, conn))
{
conn.Open();
cmd.Parameters.Add("#Search_Term", SqlDbType.VarChar, search.Length).Value = "%" + search + "%";
dt.Load(cmd.ExecuteReader());
return dt;
}
}
}
PeopleList.aspx.cs:
protected void SearchButton_Click(object sender, EventArgs e)
{
if (SearchTextbox.Text == null || SearchTextbox.Text == "")
{
PeopleListLabel.Text = "Please enter a search term!";
}
else
{
Phonelist.DataSource = Database.SearchButton(SearchTextbox.Text);
Phonelist.DataBind();
}
}
SQL Stored Procedure:
print 'SearchTerm'
if exists (select * from sys.objects where object_id = object_id(N'[SeachTerm]') AND type in (N'P', N'PC'))
drop procedure SearchTerm
go
create procedure SearchTerm
#Search_Term varchar(64) = null
as
begin
set nocount on;
SELECT first_name, last_name, email_address, gender, home_address, home_city, home_state, home_zip_code, telephone_number
FROM person
WHERE first_name LIKE #Search_Term OR last_name LIKE #Search_Term
end
You need to enclose the search parameter within single quotes.
Replace This:
cmd.Parameters.Add("#Search_Term", SqlDbType.VarChar, search.Length).Value
= "%" + search + "%";
With This:
cmd.Parameters.Add("#Search_Term", SqlDbType.VarChar, search.Length).Value
= "'%" + search + "%'";
you are missing commandType.
static public DataTable SearchButton(string search)
{
using (var conn = new SqlConnection(DatabaseConnectionString))
{
var dt = new DataTable();
const string searchQuery = "exec SearchTerm";
using (var cmd = new SqlCommand(searchQuery, conn))
{
conn.Open();
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.Add("#Search_Term", SqlDbType.VarChar, search.Length).Value = "'%" + search + "%'";
dt.Load(cmd.ExecuteReader());
return dt;
}
}
}
I just don't know how to check if the users exists in the database and stop it from inserting a new row to the db (which will cause an error as I set the user to be a primary key)
protected void Button1_Click1(object sender, EventArgs e)
{
{
OleDbConnection myconnection = new OleDbConnection();
myconnection.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|Event.mdb";
myconnection.Open();
OleDbCommand myCommand = new OleDbCommand();
myCommand.Connection = myconnection;
myCommand.CommandType = CommandType.Text;
string query = string.Format("SELECT COUNT(*) FROM users WHERE uname = '{0}'");
myCommand.CommandText = query;
try
{
int amountOfUsers = (int)myCommand.ExecuteScalar();
if (amountOfUsers < 1)
{
String myQuery = "insert into users (uname,upassword,email,type) Values ('" + UserName.Text + "','" + Password.Text + "' ,'" + Email.Text + "',' user');";
myCommand.CommandText = myQuery;
myCommand.ExecuteNonQuery();
Label1.Text = "user registered";
}
else
{
Label1.Text = "user already exists";
UserName.Text = "";
Email.Text = "";
}
}
finally
{
myconnection.Close();
}
}
}
correct your query:
query = string.Format("SELECT COUNT(*) FROM users WHERE uname = '{0}'" ,UserName.Text );
Your question isn't clear at all but I can suggest a few things..
First of all, I think you forget to use your uname as a second parameter in your:
string query = string.Format("SELECT COUNT(*) FROM users WHERE uname = '{0}'");
line. You used {0} but never point any value to this parameter. (I assume you don't have a username called {0}) Like;
string query = string.Format("SELECT COUNT(*) FROM users WHERE uname = '{0}'", UserName.Text);
As a second, please always use parameterized queries. This kind of string concatenations are open for SQL Injection attakcs.
Like;
String myQuery = "insert into users (uname,upassword,email,type) Values (#uname, #upassword, #email, #type)";
OleDbCommand myCommand = new OleDbCommand(myQuery);
myCommand.Parameters.AddWithValue("#uname", UserName.Text);
myCommand.Parameters.AddWithValue("#upassword", Password.Text);
myCommand.Parameters.AddWithValue("#uname", Email.Text);
myCommand.Parameters.AddWithValue("#uname", "user");
i want to check if the username in UserName.Text is availble in the
data base or no and if it does i want to stop from inserting new data
Than you should use SELECT first to check your username is exist in your database or not like;
string query = string.Format("SELECT * FROM users WHERE uname = '{0}'", UserName.Text);
OleDbCommand myCommand = new OleDbCommand();
myCommand.CommandText = query;
SqlDataReader reader = myCommand.ExecuteReader();
if(reader.HasRows)
{
//Your username exist in your database
}
else
{
//Doesn't exist
}
you have missing the parameter uname , you have pass the text of UserName textbox to uname
for eg
"SELECT COUNT(*) FROM users WHERE uname='" + UserName.Text +"'
My code:
// Get Connection String
string conn = WebConfigurationManager.ConnectionStrings["GraduatesConnectionString"].ToString();
// Create connection object
SqlConnection connection = new SqlConnection(conn);
SqlCommand command = connection.CreateCommand();
try
{
// Open the connection.
connection.Open();
// Execute the insert command.
command.CommandText = ("INSERT INTO PersonalInfo(Id,Name,LastName,ContactNumber, Address,Gender, Date_Of_Birth) VALUES(\'"
+ (this.txtID.Text + ("\',\'"
+ (this.txtName.Text + ("\',\'"
+ (this.txtLastName.Text + ("\',\'"
+ (this.txtContactNumber.Text + ("\',\'"
+ (this.txtAddress.Text + ("\',\'"
+ (this.gender + ("\',\'"
+ (this.txtDateofBirth.Text + ("\',\'"
)))));
command.ExecuteNonQuery();
}
finally
{
// Close the connection.
connection.Close();
}
using (SqlConnection connection = new SqlConnection(connectionString))
using (SqlCommand command = connection.CreateCommand())
{
command.CommandText = "INSERT INTO PersonalInfo (Id, Name, LastName, ContactNumber, Address, Gender, Date_Of_Birth) VALUES (#Id, #Name, #LastName, #LastName, #Address, #Gender, #DateOfBirth)";
command.Parameters.AddWithValue("#Id", txtID.Text);
...
connection.Open();
command.ExecuteNonQuery();
}
You are missing a closing ) after txtDateofBirth so your statement is incomplete.
BUT please take note of the comment of #podiluska. This code is really easy to abuse. Suppose I enter something like the following text in txtDateofBirth:
;DROP TABLE PersonalInfo;
You then get a query like:
INSERT INTO PersonalInfo(...)
VALUES (...);DROP TABLE PersonalInfo;
So please use parameterized queries as described by #abatishchev.
I'd be tempted to change your code to:
string conn = WebConfigurationManager.ConnectionStrings["GraduatesConnectionString"].ToString();
// Create connection object
using(SqlConnection connection = new SqlConnection(conn))
{
string queryText = "INSERT INTO PersonalInfo(Id,Name,LastName,ContactNumber, Address,Gender, Date_Of_Birth) VALUES(#id,#name,#lastName,#contactNumber, #address,#gender, #date_Of_Birth)";
using(SqlCommand command = new SqlCommand(queryText, connection))
{
try
{
// Open the connection.
connection.Open();
command.Parameters.AddWithValue("#id", this.txtID.Text);
command.Parameters.AddWithValue("#name", this.txtName.Text);
command.Parameters.AddWithValue("#lastName", this.txtLastName.Text);
command.Parameters.AddWithValue("#contactNumber", this.txtContactNumber.Text);
command.Parameters.AddWithValue("#address", this.txtAddress.Text);
command.Parameters.AddWithValue("#gender",this.gender );
command.Parameters.AddWithValue("#date_Of_Birth", this.txtDateofBirth.Text);
command.ExecuteReader();
}
finally
{
// Close the connection.
if(connection.State != ConnectionState.Closed)
connection.Close();
}
}
}