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
Related
I have the following code that fails at the if (!rdr.Read()), and I can't see what I am doing wrong. When I look in the database using the value in fullPath, the record exists. Here's my code:
Song song = new Song();
connectionManager = new ConnectionManager();
try
{
using (SqlConnection conn = new SqlConnection(connectionManager.ConnectionString))
{
conn.Open();
string query = $"SELECT * FROM Songs WHERE FullPath LIKE '#FullPath%'";
using (SqlCommand queryString = new SqlCommand(query, conn))
{
queryString.Parameters.Add("#FullPath", SqlDbType.NVarChar, 300).Value = fullPath;
SqlDataReader rdr = queryString.ExecuteReader();
if (!rdr.Read())
{
throw new InvalidOperationException("No records were returned.");
}
song.Title = rdr["Title"].ToString();
song.Artist = rdr["Artist"].ToString();
song.Genre = rdr["Genre"].ToString();
song.Album = rdr["Album"].ToString();
song.Year = (uint)rdr["Year"];
song.Length = rdr["Length"].ToString();
song.FullPath = rdr["FullPath"].ToString();
}
conn.Close();
}
}
catch (Exception ex)
{
Logger.log.Error($"Error getting song: {fullPath}\n", ex);
}
return song;
The #FullPath placeholder for the parameter is not included in the SQL string correctly. When you use parameters, you do not put them in single-quotes. You want this:
string query = "SELECT * FROM Songs WHERE FullPath LIKE #FullPath + '%'";
Alternatively, you could do this:
string query = "SELECT * FROM Songs WHERE FullPath LIKE #FullPath";
// ...
queryString.Parameters.Add("#FullPath", SqlDbType.NVarChar, 300).Value = fullPath + "%";
Remember, parameterized queries are more than a simple sanitization + string substitution. Rather, it quarantines the data inside a variable. Therefore the SQL code must treat the placeholder as an SQL variable. What you had was just a string literal where the value happened to match the parameter name.
That's as far as I got. There may be other errors, too. If you want better help, post the actual error message.
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";
here is my code:
private void searchInDatabase()
{
MySqlConnection c = new MySqlConnection("datasource=localhost; username=root; password=123456; port=3306");
MySqlCommand mcd;
MySqlDataReader mdr;
String query;
try
{
c.Open();
query = "SELECT * FROM test.classmates WHERE first_name ='"+searchName.Text+"'";
mcd = new MySqlCommand(query, c);
mdr = mcd.ExecuteReader();
if(mdr.Read())
{
firstName.Text = mdr.GetString("first_name");
middleName.Text = mdr.GetString("middle_name");
lastName.Text = mdr.GetString("last_name");
age.Text = mdr.GetString("age");
}
else
{
MessageBox.Show("Result Not Found");
}
}
catch(Exception error)
{
MessageBox.Show("Error: "+error.Message);
}
finally
{
c.Close();
}
}
I would like to ask for a help if I have missed on anything or I am doing it wrong. If you have free time, I will much appreciate it if you will comment the perfect way to do I implement this problem: I want to get data from MySQL then put it in a textbox.
According to MSDN you need to pass the column number as parameter
public override string GetString(int i)
So try to pass the column number (starts from 0) of your column name. Assuming the first_name is the first column of your table then
firstName.Text = mdr.GetString(0);
UPDATE
Try to use MySqlConnectionStringBuilder
MySqlConnectionStringBuilder conn_string = new MySqlConnectionStringBuilder();
conn_string.Server = "serverip/localhost";
conn_string.UserID = "my_user";
conn_string.Password = "password";
conn_string.Database = "my_db";
MySqlConnection conn = new MySqlConnection(conn_string.ToString();
First of all look at this sample of connection string and change your connection string:
'Server=myServerAddress;Port=1234;Database=myDataBase;Uid=myUsername;Pwd=myPasswor;'
If connection is OK send erorr message or full exception.
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);"
I have the following code:
try
{
//Create connection
SQLiteConnection conn = DBConnection.OpenDB();
//Verify user input, normally you give dbType a size, but Text is an exception
var uNavnParam = new SQLiteParameter("#uNavnParam", SqlDbType.Text) { Value = uNavn };
var bNavnParam = new SQLiteParameter("#bNavnParam", SqlDbType.Text) { Value = bNavn };
var passwdParam = new SQLiteParameter("#passwdParam", SqlDbType.Text) {Value = passwd};
var pc_idParam = new SQLiteParameter("#pc_idParam", SqlDbType.TinyInt) { Value = pc_id };
var noterParam = new SQLiteParameter("#noterParam", SqlDbType.Text) { Value = noter };
var licens_idParam = new SQLiteParameter("#licens_idParam", SqlDbType.TinyInt) { Value = licens_id };
var insertSQL = new SQLiteCommand("INSERT INTO Brugere (navn, brugernavn, password, pc_id, noter, licens_id)" +
"VALUES ('#uNameParam', '#bNavnParam', '#passwdParam', '#pc_idParam', '#noterParam', '#licens_idParam')", conn);
insertSQL.Parameters.Add(uNavnParam); //replace paramenter with verified userinput
insertSQL.Parameters.Add(bNavnParam);
insertSQL.Parameters.Add(passwdParam);
insertSQL.Parameters.Add(pc_idParam);
insertSQL.Parameters.Add(noterParam);
insertSQL.Parameters.Add(licens_idParam);
insertSQL.ExecuteNonQuery(); //Execute query
//Close connection
DBConnection.CloseDB(conn);
//Let the user know that it was changed succesfully
this.Text = "Succes! Changed!";
}
catch(SQLiteException e)
{
//Catch error
MessageBox.Show(e.ToString(), "ALARM");
}
It executes perfectly, but when I view my "brugere" table, it has inserted the values: '#uNameParam', '#bNavnParam', '#passwdParam', '#pc_idParam', '#noterParam', '#licens_idParam' literally. Instead of replacing them.
I have tried making a breakpoint and checked the parameters, they do have the correct assigned values. So that is not the issue either.
I have been tinkering with this a lot now, with no luck, can anyone help?
Oh and for reference, here is the OpenDB method from the DBConnection class:
public static SQLiteConnection OpenDB()
{
try
{
//Gets connectionstring from app.config
const string myConnectString = "data source=data;";
var conn = new SQLiteConnection(myConnectString);
conn.Open();
return conn;
}
catch (SQLiteException e)
{
MessageBox.Show(e.ToString(), "ALARM");
return null;
}
}
You should remove the quotes around your parameter names in the INSERT statement.
So instead of
VALUES ('#uNameParam', '#bNavnParam', '#passwdParam', '#pc_idParam',
'#noterParam', '#licens_idParam')
use
VALUES (#uNameParam, #bNavnParam, #passwdParam, #pc_idParam,
#noterParam, #licens_idParam)
Thanks to rwwilden and Jorge Villuendas, the answer is:
var insertSQL = new SQLiteCommand("INSERT INTO Brugere (navn, brugernavn, password, pc_id, noter, licens_id)" +
" VALUES (#uNavnParam, #bNavnParam, #passwdParam, #pc_idParam, #noterParam, #licens_idParam)", conn);
insertSQL.Parameters.AddWithValue("#uNavnParam", uNavn);
insertSQL.Parameters.AddWithValue("#bNavnParam", bNavn);
insertSQL.Parameters.AddWithValue("#passwdParam", passwd);
insertSQL.Parameters.AddWithValue("#pc_idParam", pc_id);
insertSQL.Parameters.AddWithValue("#noterParam", noter);
insertSQL.Parameters.AddWithValue("#licens_idParam", licens_id);
insertSQL.ExecuteNonQuery(); //Execute query
When you use System.Data.SqlClient then you provide parameter types from System.Data.SqlDbType enumeration.
But if you use System.Data.SQLite then you have to use **System.Data.DbType** enumeration.
replace
VALUES ('#uNameParam', '#bNavnParam',
'#passwdParam', '#pc_idParam',
'#noterParam', '#licens_idParam')
with
VALUES (?, ?, ?, ?, ?, ?)