How to use SELECT + parameter + FROM in SQL database? - c#

I want to know if it is possible to create a query like that:
SELECT :parameterA, :paramaterB
FROM *someTable*;
The idea is to use some structure like that instead of making some sort of string or something like that.
I´m working with SQL database and a C# project in Visual Studio 2019.
So far I have this code:
public List<V_Requerimientos> GetData(int idEmpresa, string columns)
{
List<V_Requerimientos> result = null;
try
{
var dyParam = new OracleDynamicParameters();
dyParam.Add("idEmpresa", OracleDbType.Int32, ParameterDirection.Input, value: idEmpresa);
var conn = this.GetConnection();
if (conn.State == ConnectionState.Closed)
{
conn.Open();
}
if (conn.State == ConnectionState.Open)
{
string query = "SELECT " + columns + "FROM V_REQUERIMIENTOS " +
"WHERE EMPR_CODIGO = :idEmpresa AND ETAR_CODIGO <> 4";
result= conn.Query<V_Requerimientos>(query, dyParam).ToList();
conn.Close();
}
}
catch (Exception e)
{
throw e;
}
return result;
}
where idEmpresa is the PK of the object selected in the front, and columns is a string which contains the columns I want to select for that object.
I was wondering if there is anyway for replace columns for parameters sent to the method instead of using the concatenated query as I have at the moment.

SQL parameters are used to specify value in the where clause. You would not use parameters for column names. Your query should look more like this.
string colA = "Customer Id";
string colB = "Customer Name";
string sql = $"Select [{colA}], [{colB}] from table";

Related

Exporting TERADATA's 'show table/view' into C# Visual Studio

I have an issue with storing teradata's query in c#.
I need to store 'show table/view' in any kind of C# data types. So far I have tried char[], var, string. No luck. It stores something but definitely not the thing I need. I'm not using the 'show ...' syntax. Just getting the DDL from dbc like this
select RequestText
from dbc.tablesv
where databasename = 'MyDatabse'
and tablename = 'MyTable';
And here is the code of my C#:
using (TdConnection cn = new TdConnection())
{
try
{
cn.ConnectionString = ConnectionStringBuilder.ConnectionString;
cn.Open();
Console.WriteLine("Connected to: " + connectionStringBuilder.DataSource);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
TdCommand cmd1 = cn.CreateCommand();
cmd1.CommandText = "select RequestText from dbc.tablesv where databasename = 'MyDatabase' and tablename = 'MyTable';";
using (TdDataReader reader1 = cmd1.ExecuteReader())
{
reader1.Read();
var RequestedText = reader1.GetString(0);
Console.WriteLine(RequestedText);
cn.Close();
Console.ReadLine();
}
}
All I get is some weird string that is not the one I get in teradata.
Moreover If I query to select any other column and store it in C# it works fine. To check the types for both columns I use this query:
select databasename, type(databasename), requesttext, type(requesttext)
from dbc.tablesv
where databasename = 'MyDatabase'
and tablename = 'MyTable';
The result is type(databasename) = varchar(128) and type(requesttext) = varchar(12500).
Thanks

How to print 2 columns retrieved from SQL Server database

Something missing with the code (I guess). I want to show the student id and name in the list box. But I see this:
I can't figure out the problems especially with the inner join.
private void button1_Click(object sender, EventArgs e)
{
string strName = "";
connect.Open();
SqlCommand command = new SqlCommand(" Select Student_tbl.StudentName, Student_tbl.StudentID, Module_tbl.ModuleID FROM[Course-Student] INNER JOIN Student_tbl ON [Course-Student].SID = Student_tbl.StudentID INNER JOIN Module_tbl ON[Course-Student].CID = Module_tbl.ModuleID WHERE(Module_tbl.ModuleID = '" + tbCourse.Text+"')",connect);
command.ExecuteNonQuery();
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
strName = reader[1].ToString();
listBox1.Items.Add(strName);
}
connect.Close();
}
You are printing retrieving from the reader only the StudentID field. Change your while loop as follows to retrieve both fields and concatenate the values:
while (reader.Read())
{
var name = reader[0].ToString();
var id = reader[1].ToString();
listBox1.Items.Add(id + " " + name);
}
You can also use String Interpolation (which is C# 6 syntactic sugar for string.Format) like this:
while (reader.Read())
{
listBox1.Items.Add($"{reader[1].ToString()} {reader[0].ToString()}");
}
Also, as for the sql statement: Do not use string concatenation to create the statement. This is susceptible for SQL Injections. Use instead Parameterized Queries

set Id equal to number contained in textbox

Hi I want to fill a combo box with names from a table where id is the number contained in textbox.The txtPartId is populated from another page as is the name in txtPart. The error I get when I run this is "Invalid column name "txtPartId"
public ReList(string Str_value, string id)//declare value
{
InitializeComponent();
txtPart.Text = Str_value;
txtPartId.Text = id.ToString();
displayRe();
}
private void displayRe()
{
try
{
sc.Open();
string Query = "select * from Re where Part_PartID =txtPartId ";
SqlCommand createCommand = new SqlCommand(Query, sc);
SqlDataReader dr = createCommand.ExecuteReader();
while (dr.Read())
{
string Name = dr.GetString(1);
cbRe.Items.Add(Name);//Displaying a list in the Combo Box
}
sc.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
The quick and dirty answer is to make the following change:
string Query = "select * from Re where Part_PartID = " + txtPartId.Text;
assuming Part_PartID is an integer.
If it is a string then you can use:
string Query = string.Format("select * from Re where Part_PartID = '{0}'", txtPartId.Text);
The compiler is not going to inject the value of the text in txtPartId into your query string for you.
However, that introduces the scope for SQL injection, so I strongly suggest you parameterize your query. There are many examples of this on SO.

no update on sql server database. No errors just no results

//the #Question column name needs to change according to the checkbox. For example Checkbox1 - Question1
SqlConnection con = new SqlConnection(...);
String sql = "UPDATE INQUIRY2 set #Question = #str WHERE email = #email AND base = #base;";
SqlCommand cmd = new SqlCommand(sql, con);
con.Open();
//checkbox2 - question 2
//if (CheckBox3.Checked == true)
//{
// str = str + CheckBox3 + 'x';
//}
DataTable theDataTable = null;
// Verify that dt is actually in session before trying to get it
if(Session["dt"] != null)
{
theDataTable = Session["dt"] as DataTable;
}
//Verify that the data table is not null
if(theDataTable != null)
{
email = theDataTable.Rows[0]["email"].ToString();
base1 = theDataTable.Rows[0]["base"].ToString();
}
//checkbox1 - question 1
if (CheckBox9.Checked == true)
{
str = str + CheckBox9.Text + 'x';
strQuestOne = theDataTable.Columns["Question1"].ToString();
}
cmd.Parameters.AddWithValue("#email", email);
cmd.Parameters.AddWithValue("#str", str);
cmd.Parameters.AddWithValue("#Question", strQuestOne);
cmd.Parameters.AddWithValue("#base", base1);
cmd.ExecuteNonQuery();
con.Close();
You are using a parameter for a column name. Database objects (columns names, tables, stored procedures or any other objects) cannot be passed as parameters. Only actual values for columns or variables can be parameters. You need to build your SQL statement dynamically in this case:
String sql ="UPDATE INQUIRY2 set " + strQuestOne + "= #str WHERE email = ...
But now you should be carefull because you code is at risk of SQL injection attack.
Your SQL uses #param type in the string.
If you are looking to execute a stored procedure of some sort to negate most sql injection attacks on a website you might want to consider calling a stored procedure and adding SqlCommand.Parameter to the SqlCommand.Parameters Collection.
Otherwise if you want to just execute the sql you should do
string sql = String.Format("UPDATE TABLE set COLUMN = {0} where OTHERCOLUMN = {1}", varValue, varWhere);

SQL Syntax Error (INSERT command)

I have a form with a text box and button, such that when the user clicks the button, the specified name in the text box is added to a table in my sql database. The code for the button is as follows:
private void btnAddDiaryItem_Click(object sender, EventArgs e)
{
try
{
string strNewDiaryItem = txtAddDiaryItem.Text;
if (strNewDiaryItem.Length == 0)
{
MessageBox.Show("You have not specified the name of a new Diary Item");
return;
}
string sqlText = "INSERT INTO tblDiaryTypes (DiaryType) VALUES = ('" + strNewDiaryItem + "');";
cSqlQuery cS = new cSqlQuery(sqlText, "non query");
PopulateInitialDiaryItems();
MessageBox.Show("New Diary Item added succesfully");
}
catch (Exception ex)
{
MessageBox.Show("Unhandled Error: " + ex.Message);
}
}
The class cSqlQuery is a simple class that executes various T-SQL actions for me and its code is as follows:
class cSqlQuery
{
public string cSqlStat;
public DataTable cQueryResults;
public int cScalarResult;
public cSqlQuery()
{
this.cSqlStat = "empty";
}
public cSqlQuery(string paramSqlStat, string paramMode)
{
this.cSqlStat = paramSqlStat;
string strConnection = BuildConnectionString();
SqlConnection linkToDB = new SqlConnection(strConnection);
if (paramMode == "non query")
{
linkToDB.Open();
SqlCommand sqlCom = new SqlCommand(paramSqlStat, linkToDB);
sqlCom.ExecuteNonQuery();
linkToDB.Close();
}
if (paramMode == "table")
{
using (linkToDB)
using (var adapter = new SqlDataAdapter(cSqlStat, linkToDB))
{
DataTable table = new DataTable();
adapter.Fill(table);
this.cQueryResults = table;
}
}
if (paramMode == "scalar")
{
linkToDB.Open();
SqlCommand sqlCom = new SqlCommand(paramSqlStat, linkToDB);
this.cScalarResult = (Int32)sqlCom.ExecuteScalar();
linkToDB.Close();
}
}
public cSqlQuery(SqlCommand paramSqlCom, string paramMode)
{
string strConnection = BuildConnectionString();
SqlConnection linkToDB = new SqlConnection(strConnection);
paramSqlCom.Connection = linkToDB;
if (paramMode == "table")
{
using (linkToDB)
using (var adapter = new SqlDataAdapter(paramSqlCom))
{
DataTable table = new DataTable();
adapter.Fill(table);
this.cQueryResults = table;
}
}
if (paramMode == "scalar")
{
linkToDB.Open();
paramSqlCom.Connection = linkToDB;
this.cScalarResult = (Int32)paramSqlCom.ExecuteScalar();
linkToDB.Close();
}
}
public string BuildConnectionString()
{
cConnectionString cCS = new cConnectionString();
return cCS.strConnect;
}
}
The class works well throughout my application so I don't think the error is in the class, but then I can't be sure.
When I click the button I get the following error message:
Incorrect syntax near =
Which is really annoying me, because when I run the exact same command in SQL Management Studio it works fine.
I'm sure I'm missing something rather simple, but after reading my code through many times, I'm struggling to see where I have gone wrong.
you have to remove = after values.
string sqlText = "INSERT INTO tblDiaryTypes (DiaryType) VALUES ('" + strNewDiaryItem + "');"
and try to use Parameterized queries to avoid Sql injection. use your code like this. Sql Parameters
string sqlText = "INSERT INTO tblDiaryTypes (DiaryType) VALUES (#DairyItem);"
YourCOmmandObj.Parameters.AddwithValue("#DairyItem",strNewDiaryIItem)
Remove the = after VALUES.
You do not need the =
A valid insert would look like
INSERT INTO table_name (column1, column2, column3,...)
VALUES (value1, value2, value3,...)
Source: http://www.w3schools.com/sql/sql_insert.asp
Please use following:
insert into <table name> Values (value);
Remove "=", and also i would recommend you to use string.format() instead of string concatenation.
sqlText = string.format(INSERT INTO tblDiaryTypes (DiaryType) VALUES ('{0}'), strNewDiaryItem);"

Categories