I've looked through the other questions related to this, but I'm having a different issue. I can't get a specific item to return, it only returns my column name. How do I get the item to return?
public static string GetOneFieldRecord(string field, string companyNum)
{
DataSet ds = new DataSet();
SqlCommand comm = new SqlCommand();
string strSQL = "SELECT #FieldName FROM Companies WHERE CompanyNum = #CompanyNum";
SqlConnection conn = new SqlConnection();
conn.ConnectionString = #connstring;
comm.Connection = conn;
comm.CommandText = strSQL;
comm.Parameters.AddWithValue("#FieldName", field);
comm.Parameters.AddWithValue("#CompanyNum", companyNum);
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = comm;
conn.Open();
da.Fill(ds, "CompanyInfo");
conn.Close();
return ds.Tables[0].Rows[0].ItemArray[0].ToString();
}
I've also tried
return ds.Tables[0].Rows[0][0].ToString();
I'm just getting whatever is in the field variable.
If I pass in ("CompanyName", 33), it returns "CompanyName".
Your query (in sql profiler) is
SELECT 'CompanyName' FROM Сompanies WHERE СompanyNum = 33
So it returns exactly "CompanyName" string. You cannot pass column name as sqlparameter. You should do something like
public static string GetOneFieldRecord(string field, string companyNum)
{
DataSet ds = new DataSet();
SqlCommand comm = new SqlCommand();
string strSQL = string.Format("SELECT {0} FROM Companies WHERE CompanyNum = #CompanyNum", field);
SqlConnection conn = new SqlConnection();
conn.ConnectionString = #connstring;
comm.Connection = conn;
comm.CommandText = strSQL;
comm.Parameters.AddWithValue("#FieldName", field);
comm.Parameters.AddWithValue("#CompanyNum", companyNum);
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = comm;
conn.Open();
da.Fill(ds, "CompanyInfo");
conn.Close();
return ds.Tables[0].Rows[0].ItemArray[0].ToString();
}
But this code can be used for SQL injection.
To avoid Sql injection, you could check that fieldName in field variable is one of the table columns.
Or You could get SELECT * FROM Сompanies WHERE СompanyNum = #CompanyNum and get value of named column from datatable:
public static string GetOneFieldRecord(string field, string companyNum)
{
DataSet ds = new DataSet();
SqlCommand comm = new SqlCommand();
string strSQL = "SELECT * FROM Companies WHERE CompanyNum = #CompanyNum";
SqlConnection conn = new SqlConnection();
conn.ConnectionString = #connstring;
comm.Connection = conn;
comm.CommandText = strSQL;
comm.Parameters.AddWithValue("#FieldName", field);
comm.Parameters.AddWithValue("#CompanyNum", companyNum);
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = comm;
conn.Open();
da.Fill(ds, "CompanyInfo");
conn.Close();
return ds.Tables[0].Rows[0][field].ToString();
}
Related
I have problem to get specific value from sql server with parameter can anybody explain me why it works on winfom but not on wpf and how i can fix it
my code:
private void UpdateItems()
{
COMBOBOX1.Items.Clear();
SqlConnection conn = new SqlConnection(Properties.Settings.Default.constring.ToString());
SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM CLIENT where cod_cli='some_specific_string'", conn);
DataSet ds = new DataSet();
da.Fill(ds, "CLIENT");
COMBOBOX1.ItemsSource = ds.Tables[0].DefaultView;
COMBOBOX1.DisplayMemberPath = ds.Tables[0].Columns["FR"].ToString();
COMBOBOX1.SelectedValuePath = ds.Tables[0].Columns["FC"].ToString();
}
The program when execute this function crash with error:
System.Data.SqlClient.SqlException: 'Invalid column name
'some_specific_string'.'
the solution is
SqlConnection sqlConnection = new SqlConnection(Properties.Settings.Default.constring.ToString());
{
SqlCommand sqlCmd = new SqlCommand("SELECT * FROM CLIENTS where cod_cli=#cod", sqlConnection);
sqlCmd.Parameters.AddWithValue("#cod", cod_cli.Text);
sqlConnection.Open();
SqlDataReader sqlReader = sqlCmd.ExecuteReader();
while (sqlReader.Read())
{
COMBOBOX1.Items.Add(sqlReader["FR"].ToString());
}
sqlReader.Close();
}
The query doesn't recognize string as parameter but adding as SQL parameter it works.
SqlConnection conn = new SqlConnection(Properties.Settings.Default.constring.ToString());
conn.Open();
SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM CLIENT where cod_cli='some_specific_string'", conn);
DataSet ds = new DataSet();
da.Fill(ds, "CLIENT");
//Populate the combobox
COMBOBOX1.ItemsSource = ds.Tables[0].DefaultView;
COMBOBOX1.DisplayMemberPath = "FR";
COMBOBOX1.SelectedValuePath = "FC";
where "FR" and "FC" are existing columns in your SELECT Query.
I am currently fetching a dataset from following query select * from TableName WHERE ColumnName ='values''s' query executes without any error and return dataset was empty rows. When i execute the same in SQL Worksheets it return data
Following code for ref.
string sqlQuery = "select * from TableName WHERE Name ='McNaught''s'";
SqlConnection conn = new SqlConnection(ConnectionString);
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = sqlQuery;
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = cmd;
DataSet ds = new DataSet();
conn.Open();
adapter.Fill(ds);
conn.Close();
Please try this:
string sqlQuery = 'SELECT * FROM TableName WHERE Name ="McNaught\'s"'
The Problem is you need to provide Escape Sequence before the second ' so that compiler can distinguish between the previous apostrophe. Try this.
string sqlQuery = "select * from TableName WHERE Name ='McNaught'\'s'";
SqlConnection conn = new SqlConnection(ConnectionString);
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = sqlQuery;
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = cmd;
DataSet ds = new DataSet();
conn.Open();
adapter.Fill(ds);
conn.Close();
Try this it will work with \ escape sequence.
string sqlQuery = "select * from TableName WHERE Name ='McNaught\"s'";
how am i going prevent "lesson Title" from duplicating in database when user input duplicate data?
SqlConnection cnn = new SqlConnection();
SqlCommand cmd = new SqlCommand();
SqlDataAdapter da = new SqlDataAdapter();
SqlCommandBuilder cb = new SqlCommandBuilder(da);
DataSet ds = new DataSet();
cnn.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["Project1ConnectionString"].ConnectionString;
cnn.Open();
cmd.CommandText = "select * from Lesson";
cmd.Connection = cnn;
da.SelectCommand = cmd;
da.Fill(ds, "Lesson");
DataRow drow = ds.Tables["Lesson"].NewRow();
drow["TopicID"] = DropDownList1.Text;
drow["LessonTitle"] = TextBox1.Text;
drow["LessonDate"] = DateTime.Now;
ds.Tables["Lesson"].Rows.Add(drow);
da.Update(ds, "Lesson");
That kind of uniqueness should be enforced by the database. Add a unique constraint to your table:
CREATE UNIQUE INDEX UK_Lesson_Title ON Lesson (Title)
You can create a function to check the duplicate LessonTitle.
Explanantion: here i have created a function called checkDuplicateTitle().
this function takes AllRows of a LessonTable as DataRowCollection and LessonTitle to be verified as inputs.
it will check the LessonTitle of each and every row.
if given LessonTitle is matched with existing Titles from Table then this function returns true else returns false.
if the returned value is true we will ignore the updating the table with new row as LessonTitle is already Existing otherwise we will add it.
Code as below:
void UpdateLessonTable()
{
SqlConnection cnn = new SqlConnection();
SqlCommand cmd = new SqlCommand();
SqlDataAdapter da = new SqlDataAdapter();
SqlCommandBuilder cb = new SqlCommandBuilder(da);
DataSet ds = new DataSet();
cnn.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["Project1ConnectionString"].ConnectionString;
cnn.Open();
cmd.CommandText = "select * from Lesson";
cmd.Connection = cnn;
da.SelectCommand = cmd;
da.Fill(ds, "Lesson");
if (!checkDuplicateTitle(ds.Tables["Lesson"].Rows, textBox1.Text.ToString()))
{
DataRow drow = ds.Tables["Lesson"].NewRow();
drow["TopicID"] = DropDownList1.Text;
drow["LessonTitle"] = TextBox1.Text;
drow["LessonDate"] = DateTime.Now;
ds.Tables["Lesson"].Rows.Add(drow);
da.Update(ds, "Lesson");
}
else
{
//you can display some warning here
// MessageBox.Show("Duplicate Lesson Title!");
}
}
//function for checking duplicate LessonTitle
bool checkDuplicateTitle(DataRowCollection rowTitle,String newTitle)
{
foreach (DataRow row in rowTitle)
{
if(row["LessonTitle"].Equals(newTitle))
return true;
}
return false;
}
i'm having an error " Object reference not set to an instance of an object. "
// Define the ADO.NET objects.
SqlConnection con = new SqlConnection(connectionString);
string selectSQL = "SELECT * FROM tbl_lecturer_project";
SqlCommand cmd = new SqlCommand(selectSQL, con);
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
DataSet dsPubs = new DataSet();
// Try to open database and read information.
try
{
con.Open();
adapter.Fill(dsPubs, "tbl_lecturer_project");
// This command is still linked to the data adapter.
cmd.CommandText = "SELECT * FROM tbl_student_project_choice";
adapter.Fill(dsPubs, "tbl_student_project_choice");
cmd.CommandText = "SELECT * FROM tbl_team";
adapter.Fill(dsPubs, "tbl_team");
DataRelation SCoiceLec = new DataRelation("SCoiceLec", dsPubs.Tables["tbl_lecturer_project"].Columns["lecturerProjectId"], dsPubs.Tables["student_project_choice"].Columns["choiceProjectId"]);
DataRelation SChoiceNTeam = new DataRelation("SChoiceNTeam",dsPubs.Tables["student_project_choice"].Columns["choiceGroupId"], dsPubs.Tables["tbl_team"].Columns["teamId"]);
please help. i want to retrieve data from all 3 tables.
There are a number of problems with your code. Here is one:
adapter.Fill(dsPubs, "tbl_lecturer_project");
should be
adapter.Fill(dsPubs);
I think what you want is this:
string selectSQL = #"SELECT * FROM tbl_lecturer_project;
SELECT * FROM tbl_student_project_choice;
SELECT * FROM tbl_team";
using(SqlConnection con = new SqlConnection(connectionString))
{
con.Open();
using(SqlCommand cmd = new SqlCommand(selectSQL, con))
{
using(SqlDataAdapter adapter = new SqlDataAdapter(cmd))
{
DataSet dsPubs = new DataSet();
adapter.Fill(dsPubs);
// use dataset.
}
}
}
The three tables will have the names Table, Table1, and Table2
How to convert a C# DateTime variable into Enum of SqlDataType.DateTime?
How to consume that enum into a connection string?
Is doing something like this correct?
string str = "SELECT * FROM TABLE WHERE CreateDt " + <that enum>;
SqlConnection Connection = new SqlConnection (<connection setting>);
Table = new DataTable();
SqlDataAdapter adapter = new SqlDataAdapter(str, Connection);
adapter.FillSchema(Table, SchemaType.Source);
adapter.Fill(Table);
Thank you
Your best option is to use a parameterized command:
var cmd = new SqlCommand();
cmd.Connection = conn;
DateTime MyDate = DateTime.Now;
cmd.CommandText = #"SELECT * FROM TABLE WHERE CreateDt = #MyDate";
cmd.Parameters.AddWithValue("#MyDate", #MyDate);
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = cmd;
adapter.FillSchema(Table, SchemaType.Source);
adapter.Fill(Table);
This is not tested, but how about:
string str = "SELECT * FROM TABLE WHERE CreateDt = #createDate";
SqlConnection Connection = new SqlConnection (<connection setting>);
Table mytable = new DataTable();
SqlDataAdapter adapter = new SqlDataAdapter(str, Connection);
adapter .SelectCommand.Parameters.Add("#createDate", SqlDbType.DateTime)
adapter .SelectCommand.Parameters("#createDate").Value = <Some DateTime>
adapter.FillSchema(mytable, SchemaType.Source);
adapter.Fill(Table);