I have an olap cube which i want to access. I am trying to execute mdx query. here is my simple test program:
static void Main(string[] args)
{
using (OleDbConnection cn = new OleDbConnection())
{
cn.ConnectionString = "secret";
cn.Open();
string MDX = "SELECT [Measures].[Amount] "+ " ON ROWS, " + "[Dim Client].[Common Client Name].&[test Name] "+ " ON COLUMNS " + "from [CubeName];";
OleDbCommand command = new OleDbCommand(MDX, cn);
System.Data.DataSet ds = new System.Data.DataSet();
OleDbDataAdapter adp = new OleDbDataAdapter(command);
adp.Fill(ds);
Console.WriteLine(ds.Tables[0].Rows[0][1]);
}
}
I am keep getting following error : Incorrect syntax near the keyword 'ON'. and i cant figure out what i am doing wrong. If i execute exact same query directly from management studio, cube response without errors.
In debug mode, copy the query inside string quotes ""
Try without the concatenations and maybe use the axes index numbers, also if you are using the members caption then no need to include the ampersand:
string MDX = "SELECT [Measures].[Amount] ON 0, [Dim Client].[Common Client Name].[test Name] ON 1 FROM[CubeName];";
Does this mdx execute ok in SSMS?
Related
I am attempting to Insert a Row on a Table, but I cannot seem to pass the TASK_ID as a value/variable/function into the SQL Statement. Throughout the application, to acquire TASK_ID, I use:
Dim taskID = ds.Tables("ReminderTable").Rows(Count).Field(Of Integer)("TASK_ID")
Some helpful context-code :
da.Fill(ds, "ReminderTable")
Count = ds.Tables("ReminderTable").Rows.Count - 1
Here is what I'm trying to do:
da.InsertCommand = New OleDbCommand("INSERT INTO ACTIVITY (TASK_ID, ACTIVITY_CDE, ACTIVITY_NOTE) VALUES (3827, 1, 'Reminder Sent: ' & Now)", Connection)
I keep receiving the error
No value given for one or more required parameters.
when I replace 3827 with a variable/function/reference.
The statement works as-is, but I need to replace "3827" in the above statement with the TASK_ID, but it won't accept my variable, a function or the location that I use elsewhere throughout the project to reference the same thing.
I'm working in Visual Studio 2019, using a Microsoft Access Database
Use String Interpolation
da.InsertCommand = New OleDbCommand(
$"INSERT INTO ACTIVITY (TASK_ID, ACTIVITY_CDE, ACTIVITY_NOTE)
VALUES ({taskID}, 1, 'Reminder Sent: ' & Now())", Connection)
If getting the date and time from .NET, you would be able to add that with string interpolation as well
da.InsertCommand = New OleDbCommand(
$"INSERT INTO ACTIVITY (TASK_ID, ACTIVITY_CDE, ACTIVITY_NOTE)
VALUES ({taskID}, 1, 'Reminder Sent: {DateTime.Now}')", Connection)
Try Adding the Actual Dimension to your First Line of code Like so:
Dim taskID as Integer = ds.Tables("ReminderTable").Rows(Count).Field(Of Integer)("TASK_ID")
You could also write like this:
Dim taskID as Integer = ds.Tables("ReminderTable").Rows(Count)("TASK_ID")
Hope this helps
Here is a really basic example. It is in C#, but you can easily translate it into VB. The important part is the cmd.Parameters.AddWithValue.
public int Create(EmployeeClassification classification)
{
if (classification == null)
throw new ArgumentNullException(nameof(classification), $"{nameof(classification)} is null.");
const string sql = #"INSERT INTO EmployeeClassification (EmployeeClassificationName) VALUES(#EmployeeClassificationName )";
using (var con = OpenConnection())
using (var cmd = new OleDbCommand(sql, con))
{
cmd.Parameters.AddWithValue("#EmployeeClassificationName", classification.EmployeeClassificationName);
return cmd.ExecuteNonQuery();
}
}
Source: https://grauenwolf.github.io/DotNet-ORM-Cookbook/SingleModelCrud.htm#ado.net
I try am trying to build a function that populates a table when given the name of the table and what parameter to order it by.
I think I am just making a syntax error in my SQL command but I can't find it. Please help.
public DataTable populateTable(string tableName, string orderByParameter)
{
DataTable table = new DataTable();
string connString = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
string cmdString = "SELECT * FROM (value = #tbl) ORDER BY (parameter = #obp) DESC";
using (SqlConnection conn = new SqlConnection(connString))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = conn;
cmd.CommandText = cmdString;
cmd.Parameters.AddWithValue("#tbl", tableName);
cmd.Parameters.AddWithValue("#obp", orderByParameter);
using (SqlDataAdapter ad = new SqlDataAdapter(cmd))
{
ad.Fill(table);
}
}
try
{
GridView1.DataSource = table;
GridView1.DataBind();
return table;
}
catch (Exception e)
{
Console.WriteLine(e.Message);
return null;
}
}
}
You can't have variables in table name or in 'order by' clause.
You could build the query dynamically as:
string cmdString = "SELECT * FROM [" + tableName + "] ORDER BY " + orderByParameter +" DESC";
With this you won't need to add the parameters #tbl and #obp to the command.
Note that this runs into SQL injection related vulnerabilities. So you shouldn't do this unless you are absolutely certain that the table with given name exists, and the orderByParameter is a valid expression.
I have the following code that runs on a button click:
protected void Button2_Click(object sender, EventArgs e)
{
String str = "SELECT * " +
"FROM ConcernTicket INNER JOIN Employee " +
"ON ConcernTicket.EmployeeReportedToID = Employee.EmployeeId " +
"WHERE (Employee.FirstName LIKE '%' + #search2 + '%')";
SqlCommand xp = new SqlCommand(str, vid);
xp.Parameters.Add("#search2", SqlDbType.NVarChar).Value =
TextBox1.Text;
vid.Open();
xp.ExecuteNonQuery();
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = xp;
DataSet ds = new DataSet();
da.Fill(ds, "Employee.FirstName");
GridView2.DataSource = ds;
GridView2.DataBind();
vid.Close();
}
The problem I am facing is that the search runs with no errors but instead of just returning the results where the FirstName variable matches, it displays all current Concern Tickets. I am assuming it is a fairly simple fix with the SELECT statement, but for some reason I have not been able to figure out what is going wrong. I just started working with sql so I apologize that I am having such a silly issue, any help would be appreciated, thanks!
Check that TextBox1.Text is not empty. If it is empty, the query will be:
WHERE (Employee.FirstName LIKE '%%')";
Also check that #search2 is being replaced properly. The + operator is not what you would expect in MySQL. Perhaps this is what you're looking for:
"WHERE (Employee.FirstName LIKE '%#search2%')";
Hope that helps
your problem is not the SQL query. In fact you use ExecuteNonQuery() to extract select result. ExecuteNonQuery() just returns a single integer.Please use a code like this and let me know if the problem persists.
string connetionString = null;
SqlConnection connection ;
SqlDataAdapter adapter = new SqlDataAdapter();
DataSet ds = new DataSet();
int i = 0;
connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password";
connection = new SqlConnection(connetionString);
try
{
connection.Open();
adapter.SelectCommand = new SqlCommand("Your SQL Statement Here", connection);
adapter.Fill(ds);
connection.Close();
for (i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)
{
MessageBox.Show(ds.Tables[0].Rows[1].ItemArray[1].ToString());
}
}
I am trying to access a table in Visual Studio 2012 and am using Oracle 11g as the back end.
This is my code part which is giving error:
comm = new OracleCommand();
comm.Connection = conn;
comm.CommandText = "select * from message where send_username='" + username + "' or r_username='"+username+"' order by id desc";
ds = new DataSet();
da = new OracleDataAdapter(comm.CommandText, conn);
da.Fill(ds, "message");
dt = ds.Tables["message"];
The same query when i run in SQL Command Prompt, it gives me 3 tuples as output but in this it is giving error
There is no row at position 1.
It is only giving one particular row as output no matter whatever else i do.
Any idea what I am doing wrong ??
if (ds.Tables.Count > 0 )
{
dt = ds.Tables["message"];
}
And
if (ds.Tables["message"].Rows.Count > 0)
{
}
I am trying to prevent any SQL injection in all my queries and would like to know how to put double quotes in this query. Thanks
string.Format("SELECT TOP 10 article_guid, article_title
FROM article
WHERE article.article_isdeleted = 0 AND
FREETEXT(article_title, #val)");
Step 1: Don't do this. Use a parameterized query instead.
Parameterized queries remove most of the risk associated with SQL injection attacks.
From the link:
private void CallPreparedCmd() {
string sConnString =
"Server=(local);Database=Northwind;Integrated Security=True;";
string sSQL =
"UPDATE Customers SET City=#sCity WHERE CustomerID=#sCustomerID";
using (SqlConnection oCn = new SqlConnection(sConnString)) {
using (SqlCommand oCmd = new SqlCommand(sSQL, oCn)) {
oCmd.CommandType = CommandType.Text;
oCmd.Parameters.Add("#sCustomerID", SqlDbType.NChar, 5);
oCmd.Parameters.Add("#sCity", SqlDbType.NVarChar, 15);
oCn.Open();
oCmd.Prepare();
oCmd.Parameters["#sCustomerID"].Value = "ALFKI";
oCmd.Parameters["#sCity"].Value = "Berlin2";
oCmd.ExecuteNonQuery();
oCmd.Parameters["#sCustomerID"].Value = "CHOPS";
oCmd.Parameters["#sCity"].Value = "Bern2";
oCmd.ExecuteNonQuery();
oCn.Close();
}
}
}
That being said, you can insert quotes into a string by escaping the double quotes like this:
string newstring = " \"I'm Quoted\" ";
To prevent SQL Injection you must only use SqlParameter objects for all your queries, like so:
SqlCommand command = new SqlCommand("update tblFoo set x = #x");
SqlParamter param = new SqlParameter("#x", SqlDbType.NVarChar);
param.Value = "hello\"";
command.Parameters.Add(param);
Why did you use string.Format? You are using #parameterized query and it is Type-Safe.
Use Type-Safe SQL Parameters for Data Access
I'm not sure if double quotes will help you (which you can add if you like by escaping the quote, as in \"). What I've done in the past is to be mindful of single quotes, so I performed a replace on the content of #val prior to including it in the query, as in val.Replace("'", "''").