I am trying to view the data based on the current logged in user and group them together based on current month by using the group by() and datepart() method. However, it seems that my "" is incorrect. May I know what is the proper way of doing it? Thank you.
Below are my error and the codes:
E/Error: Invalid SQL statement or JDBC escape, terminating ''' not found.
val sqlCon = SQLCon()
val current = LocalDateTime.now()
val formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd")
val formatted = current.format(formatter)
val sql : String=
"SELECT Category,eAmount,eNote,eDate FROM Expenses where Username = '" + cUser + "'" +
"AND eMonth = DATEPART(MONTH,'" + formatted + ")'" +
"AND eYear = DATEPART(YEAR,'" + formatted + ")'"
statement = connection!!.createStatement()
var rs : ResultSet = statement!!.executeQuery(sql)
while (rs.next())
{
var note : String = rs.getString("iNote") ?: ""
eList.add(ItemList(rs.getString("iCategory"), rs.getDouble("iAmount"),note,rs.getString("iDate")))
}
rs.close()
statement!!.close()
Toast.makeText(this, "Success", Toast.LENGTH_LONG).show()
Related
I have a task of loading data from a .txt file to SQL Server table using Script Component in SSIS. I have loaded that successfully using a script.
public void Main()
{
//Declare Variables
string SourceFolderPath = Dts.Variables["$Project::Landing_Zone"].Value.ToString();
string FileExtension = Dts.Variables["User::FileExtension"].Value.ToString();
string FileDelimiter = Dts.Variables["User::FileDelimiter"].Value.ToString();
string ArchiveFolder = Dts.Variables["User::ArchiveFolder"].Value.ToString();
string ColumnsDataType = Dts.Variables["User::ColumnsDataType"].Value.ToString();
string SchemaName = Dts.Variables["$Project::SchemaName"].Value.ToString();
//Reading file names one by one
string[] fileEntries = Directory.GetFiles(SourceFolderPath, "*" + FileExtension);
foreach (string fileName in fileEntries)
{
SqlConnection myADONETConnection = new SqlConnection();
myADONETConnection = (SqlConnection)(Dts.Connections["DBConn"].AcquireConnection(Dts.Transaction) as SqlConnection);
//Writing Data of File Into Table
string TableName = "";
int counter = 0;
string line;
string ColumnList = "";
//MessageBox.Show(fileName);
System.IO.StreamReader SourceFile =
new System.IO.StreamReader(fileName);
while ((line = SourceFile.ReadLine()) != null)
{
if (counter == 0)
{
ColumnList = "[" + line.Replace(FileDelimiter, "],[") + "]";
TableName = (((fileName.Replace(SourceFolderPath, "")).Replace(FileExtension, "")).Replace("\\", ""));
string CreateTableStatement = "IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[" + SchemaName + "].";
CreateTableStatement += "[" + TableName + "]')";
CreateTableStatement += " AND type in (N'U'))DROP TABLE [" + SchemaName + "].";
CreateTableStatement += "[" + TableName + "] Create Table " + SchemaName + ".[" + TableName + "]";
CreateTableStatement += "([" + line.Replace(FileDelimiter, "] " + ColumnsDataType + ",[") + "] " + ColumnsDataType + ")";
SqlCommand CreateTableCmd = new SqlCommand(CreateTableStatement, myADONETConnection);
CreateTableCmd.ExecuteNonQuery();
//MessageBox.Show(CreateTableStatement);
}
else
{
string query = "Insert into " + SchemaName + ".[" + TableName + "] (" + ColumnList + ") ";
query += "VALUES('" + line.Replace(FileDelimiter, "','") + "')";
// MessageBox.Show(query.ToString());
SqlCommand myCommand1 = new SqlCommand(query, myADONETConnection);
myCommand1.ExecuteNonQuery();
}
counter++;
}
SourceFile.Close();
}
}
Package Variable Details
But the problem is that I could load all the values from the text file to the table only with a single data type(I used nvarchar(200) as a common data type for all values). I have passed nvarchar(200) as a value in one of the package variable and I have called that in the script.
I am expecting the script component to assign a DataType to the columns by understanding the values available in the text file.
Example: The text file which I loaded into the table has got the following data.
Id,Name,Age
1,Arun,25
2,Ramesh,26
3,Anish,28
As a result a table with the name dbo.File_1 is created with columns Id, Name and Age. But all the these columns are created with the same datatype nvarchar(200) as mentioned previously.
But my requirement is that the script component should assign data types based on the values, say for example, The Column Id should be assigned with datatype int, Name should be assigned with datatype nvarchar(50) and so on. Likewise the script should assign datatypes based on any kind of values(Like Decimal, Date etc)
Is there any possible way to achieve this? Thanks in advance.
Additional Hint:
This script normally Drop and Create a new table everytime during the execution. The table name is based on the FileName.
This is shooting from the hip on this one, but maybe using tryparse:
col += int.TryParse(ID, out num)? "int" : "nvarchar(200)";
I wrote a method to delete values from a database, however when I check the rows affected the value is 0 and keeps going into the first if statement any ideas?
private void workstationDelete()
{
string query = "DELETE FROM test_revision2 where wsid = #wsid and location = '#location'";
try
{
conn = new SqlConnection(connStr);
conn.Open();
SqlCommand cmd = new SqlCommand(query, conn);
cmd.Parameters.AddWithValue("#wsid", Convert.ToInt32(wsid2text.Text));
cmd.Parameters.AddWithValue("#location", deletelocation);
cmd.ExecuteNonQuery();
int rowsaffected = cmd.ExecuteNonQuery();
if (rowsaffected == 0)
{
lblDel.Text = "Sorry Workstation: " + wsid2text.Text + " does not exist in " + deletelocation + ". Therefore it cannot be removed.";
}
else
{
lblDel.Text = "You have successfully removed Workstation: " + Convert.ToInt32(wsid2text.Text) + " in " + deletelocation;
}
conn.Close();
}
catch (SqlException)
{
lblDel.Text = "randome";
}
}
Remove the single quotation marks from '#location'. You have it ignoring the parameter and trying to match a string literal.
Aside: There are good reasons not to use AddWithValue.
The problem was I was using cmd.executeNonQuery twice the first one was returning 1 however when I initialized to a var it becomes 0. Use execute non query once - when assigning the int var.
Good afternoon, whatever your timezone is ..
My question is,
Is there a way to select all tables? just like how we select all columns?
Something like
Dim cmdsql As String = "SELECT * FROM *"
Situation:
I have 4 tables inside the database ("which I would not know the names if my client changes it") So I need a better way how to do those.
I wanna SELECT all the columns, FROM all the tables store it in a dataset, so I can iterate
if it matches the search criteria.
EDIT: This is my search code by the way.
SearchDataset.Clear()
lstSearchResults.Items.Clear()
btnSearch.Enabled = False
Dim cmdsql As String = "SELECT * FROM *" '- This variable holds the SQL command.
'-----------------------------------------
' Connect to the current connection string
'----------------------------------------
SYSTEM_MainClient.dbcon.Open()
'-----------------------------------------
' Setup the Where Clause
'----------------------------------------
If cboSearchBy.Text = "StudentID" Then
SearchAdapter = New OleDb.OleDbDataAdapter(cmdsql + " WHERE " + cboSearchBy.Text + " = " + txtSearchbox.Text, SYSTEM_MainClient.dbcon)
ElseIf cboSearchBy.Text = "Age" Then
SearchAdapter = New OleDb.OleDbDataAdapter(cmdsql + " WHERE " + cboSearchBy.Text + " = " + txtSearchbox.Text, SYSTEM_MainClient.dbcon)
Else
SearchAdapter = New OleDb.OleDbDataAdapter(cmdsql + " WHERE " + cboSearchBy.Text + " like '" + txtSearchbox.Text + "'", SYSTEM_MainClient.dbcon)
End If
SearchAdapter.Fill(SearchDataset, "SearchResults")
SYSTEM_MainClient.dbcon.Close()
If SearchDataset.Tables("SearchResults").Rows.Count > 0 Then
For i = 0 To SearchDataset.Tables("SearchResults").Rows.Count - 1
lstSearchResults.Items.Add(SearchDataset.Tables("SearchResults").Rows(i).Item("Last_Name").ToString + ", " + SearchDataset.Tables("SearchResults").Rows(i).Item("First_Name").ToString)
Next
Else
SYSTEM_MainClient.ShowInformation("No records matched with the search '" + txtSearchbox.Text + "'.", "Database Search")
txtSearchbox.Clear()
End If
btnSearch.Enabled = True
Basically what I want to happen, select all from all tables, and fill it in the dataset and iterate inside the dataset if there are matching result names based on the search criteria with my where clause.
Here this Is the code to select all the tables from the ms access database
SELECT MSysObjects.Name AS table_name FROM MSysObjects
WHERE (((Left([Name],1))<>"~") AND ((Left([Name],4))<>"MSys") AND ((MSysObjects.Type) In (1,4,6)))
order by MSysObjects.Name
Making some alteration to this query will help to select columns of table
I need to access data from a table. I have used the code like this:
string sql = "select * from bikesold "
+ "where model = '"+model+"'
+ "and mnth = '"+mnth+"' ";
The error is coming as follows:
ORA-00904: "MNTH": invalid identifier.
All the database connections are ok. I just need to confirm the Syntax for this code.
string sql = "select * from bikesold "
+ "where model = '"+model+"'"
+ "and mnth = '"+mnth+"' ";
you have missed the double quote in 2nd string.
For starters, your string is wrong. Try this instead:
string sql = "select * from bikesold "
+ "where model = '"+ model +
+ "' and mnth = '"+ mnt + "'";
Q: Does your table actually have a column named "mnth'?
This is my original code:
String sqlQuery = "SELECT * FROM data where company = '"+ Selecteditem +"'" ;
SQLiteDatabase db = this.getWritableDatabase();
Cursor c = db.rawQuery(sqlQuery, null);
if (c.moveToFirst()){
do{
temp_array.add(c.getString(c.getColumnIndex("name")) +
"," + c.getString(c.getColumnIndex("code")) +
"," + c.getString(c.getColumnIndex("company"))
);
I want to hide company on the list, I change "*" to name, code but without success, I delete " **"," + c.getString(c.getColumnIndex("company"))** " this line no success,
What to do please help me
You can just remove the company string, by replacing c.getString(c.getColumnIndex("company")) with an empty string "".
String sqlQuery = "SELECT * FROM data where company = '" + Selecteditem + "'";
SQLiteDatabase db = this.getWritableDatabase();
Cursor c = db.rawQuery(sqlQuery, null);
if (c.moveToFirst()) {
do {
temp_array.add(c.getString(c.getColumnIndex("name")) +
"," + c.getString(c.getColumnIndex("code")) +
"," + ""
);
Another solution is to select only the columnn you need:
String sqlQuery = "SELECT name, code FROM data where company = '" + Selecteditem + "'";
SQLiteDatabase db = this.getWritableDatabase();
Cursor c = db.rawQuery(sqlQuery, null);
if (c.moveToFirst()) {
do {
temp_array.add(c.getString(c.getColumnIndex("name")) +
"," + c.getString(c.getColumnIndex("code"))
);