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'?
Related
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()
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)";
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 wanted to update the values of a few columns of a database table, using queries or stored procedure, but wanted to use my C# library to alter the value.
For ex, I want the columns A,B,C of table T to be replaced with Encrypt(A), Encrypt(B) and Encrypt(C) where Encrypt is a part of a C# library.
I could have done it in a simple console application, but I have to do this process for a lot of columns in lot of tables. Could I use some SQLCLR stored procedure/query to do this process in SQL Server Management Studio?
It will be really great if someone could assist in this.
public class SP
{
[Microsoft.SqlServer.Server.SqlFunction()]
public static void Enc()
{
using (SqlConnection connection = new SqlConnection("context connection=true"))
{
connection.Open();
SqlCommand command;
SqlCommand command1;
for (int i = 0; i < 1; i++)
{
command = new SqlCommand("SELECT " + tableFieldArray[i, 1].ToString() + " FROM " + tableFieldArray[i, 0].ToString(), connection);
SqlDataReader reader = command.ExecuteReader();
using (reader)
{
while (reader.Read())
{
if (!reader.IsDBNull(0) && !String.IsNullOrEmpty(reader.GetString(0)))
{
//SqlContext.Pipe.Send("Data = " + reader.GetString(0) + "; Encrypted = " + Encrypt(reader.GetString(0)));
SqlContext.Pipe.Send("UPDATE " + tableFieldArray[i, 0].ToString() + " SET "
+ tableFieldArray[i, 1].ToString() + " = '" + Encrypt(reader.GetString(0)) + "' "
+ "WHERE " + tableFieldArray[i, 1].ToString() + " = '" + reader.GetString(0) + "'");
//query = "UPDATE " + tableFieldArray[i, 0].ToString() + " SET "
// + tableFieldArray[i, 1].ToString() + " = '" + Encrypt(reader.GetString(0)) + "' "
// + "WHERE " + tableFieldArray[i, 1].ToString() + " = '" + reader.GetString(0) + "'";
command1 = new SqlCommand("UPDATE " + tableFieldArray[i, 0].ToString() + " SET "
+ tableFieldArray[i, 1].ToString() + " = '" + Encrypt(reader.GetString(0)) + "' "
+ "WHERE " + tableFieldArray[i, 1].ToString() + " = '" + reader.GetString(0) + "'",connection);
}
}
}
SqlCommand command1 = new SqlCommand(query , connection);
command1.ExecuteNonQuery();
}
connection.Close();
}
}
public static string Encrypt(string TextFromForm)
{
//implementation
}
}
}
For some reason this question is a complete duplicate of ( Can I use SQLCLR stored procedure to update a column of a database table ( using some compiled dll) ), but assuming that other one will be closed (it should be), my answer is the same:
You can use SQLCLR to call encryption from C#, though this is the wrong approach. If you need to do a custom algorithm, you should encapsulate that into a SQLCLR function so that it can be used in an UPDATE statement or even an INSERT or SELECT or anywhere. Something like:
public class SP
{
[Microsoft.SqlServer.Server.SqlFunction(IsDeterministic = true)]
public static SqlString EncryptByAES(SqlString TextToEncrypt)
{
return DoSomething(TextToEncrypt.Value);
}
}
Then you can use that function as follows:
UPDATE tb
SET tb.FieldA = EncryptByAES(tb.FieldA)
FROM dbo.TableName tb
WHERE tb.FieldA some_test_to_determine_that_FieldA_is_not_alreay_encrypted;
BUT, before you write a custom encryption algorithm, you might want to check out the several built-in paired ENCRYPTBY / DECRYPTBY functions that might do exactly what you need:
ENCRYPTBYASYMKEY / DECRYPTBYASYMKEY
ENCRYPTBYCERT / DECRYPTBYCERT
ENCRYPTBYKEY / DECRYPTBYKEY
ENCRYPTBYPASSPHRASE / DECRYPTBYPASSPHRASE
I have an Invoice that I need to move from Pending Sales
to a Sale Journal, at the end of year to a Master Sale Journal.
Old quotes get moved to a Quote Archive as well. Quotes and Invoices
from the Sale Journal can be moved back to Pending Sales.
I want to build a class that I can pass the source and destination tables
to and move the invoice in and out of.
I have never done a Stored Procedure or pass the adapterTable to a procedure
either.
I am not sure what is the best method to approach a seedy solution is.
I am thinking a stored procedure is the way to go, but how to do a Fill and Insert?
Ideas? code examples?
Started playing with this, but not even close to a good sstart
SqlDataAdapter daPASQS = new SqlDataAdapter("SELECT * FROM " + "VF_PasQS" + " WHERE (calendar_year = " + year + ") and (inv_no_ =" +
InvNo + ") and (s = " + Series + "}", pasps);
DataSet dsPASQS = new DataSet();
daPASPR.TableMappings.Add("vf_PASQS", "invNo");
daPASPR.Fill(dsPASQS, "invNo");
BindingSource myBinding = new BindingSource(dsPASQS, "invNo");
pasps.Close();
int invNo = 0;
foreach (DataRow row in dsPASQS.Tables[0].Rows)
{
invNo = (Int32)row["invNo"];
}
Thanks,
Jerry
Been playing with the following,
string str = "select * into VF_PASPS " +
"FROM vf_PASQS " +
"WHERE (calendar_year = '" + year + "') AND (inv_no_ = '" + InvNo + "') AND (s = '" + Series + "')";
but only creats a NEW TABLE. I need to add/append to an existing table
Thanks,
Jerry
You can use the SqlBulkCopy class