how to hide a column in database - database

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"))
);

Related

There are fewer columns in the INSERT statement than values specified in the VALUES clause-SSIS

I am new to SSIS. What I am trying to do. I have some text files in a folder. I want to get data from those files and load into sql server. I am using Script Task. Here's my code.
public void Main()
{
string datetime = DateTime.Now.ToString("yyyyMMddHHmmss");
try
{
//Declare Variables
string SourceFolderPath = Dts.Variables["User::SourceFolder"].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::DataType"].Value.ToString();
string SchemaName = Dts.Variables["User::SchemaName"].Value.ToString();
//string ColumnList = "";
SqlConnection myADONETConnection = new SqlConnection();
myADONETConnection = (SqlConnection)
(Dts.Connections["PLEGO.OwyheePrac1"].AcquireConnection(Dts.Transaction) as SqlConnection);
//Reading file names one by one
string[] fileEntries = Directory.GetFiles(SourceFolderPath, "*" + FileExtension);
foreach (string fileName in fileEntries)
{
//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();
//move the file to archive folder after adding datetime to it
File.Move(fileName, ArchiveFolder + "\\" + (fileName.Replace(SourceFolderPath, "")).Replace(FileExtension, "") + "_" + datetime + FileExtension);
Dts.TaskResult = (int)ScriptResults.Success;
}
}
catch (Exception exception)
{
// Create Log File for Errors
using (StreamWriter sw = File.CreateText(Dts.Variables["User::LogFolder"].Value.ToString()
+ "\\" + "ErrorLog_" + datetime + ".log"))
{
sw.WriteLine(exception.ToString());
Dts.TaskResult = (int)ScriptResults.Failure;
}
}
}
I am getting this error:
There are fewer columns in the INSERT statement than values specified in the VALUES clause.
I think this is because in source file. some rows has null values. Below is the example
ID, Name, LastName,ContactNumber
1,'abc','yuy',09090
2,,'wxz','4535
3,,,'7565

To make a Script Component to dynamically assign a data type based on the value from a text file

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)";

Can I use SQLCLR stored procedure to update a column of a database 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

Need help in Syntax for accessing data in JSP

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'?

Syntax error: Encountered "t" at line 1, column 54

I'm getting an error that says "Syntax error: Encountered "t" at line 1, column 54"
This only seems to happen when the enhanced for loop for the History list iterates more than once. It works perfectly fine when I add one row of items, but when I add any more it gives me this error
Here is my code:
public void databaseSave( ArrayList <Patient> pList )
{
try
{
stmt = getConnection().createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
//Statement stmt = con.createStatement();
//Deletes all records from the Patient Table.
deleteAllFromPatientTable();
//Selects all the records from the Patient table.
selectAllFromPatient();
System.out.println("Before loop");
for ( Patient p: pList )
{
patientInsertSQL = "Insert Into SHAUN.PATIENT VALUES (" + p.getPatientNum() + ", '"
+ p.getPatientName() + "', '" + p.getPatientAddress() + "', '"
+ p.getPatientPhone() + "')";
res = stmt.executeUpdate(patientInsertSQL);
System.out.println(res);
ArrayList <History> tempHistList = p.getHistory();
//Deletes all the records from the history table.
deleteAllFromHistoryTable();
//Selects all the records from the history table.
selectAllFromHistory();
for ( History h: tempHistList )
{
historyInsertSQL = "Insert Into SHAUN.HISTORY VALUES (" + h.getHistID() + ", '" + h.getConditionName() + "', '" + h.getMedication() + "', '" + h.getDateOccured() + "', " + p.getPatientNum() + ")";
res = stmt.executeUpdate(historyInsertSQL);
System.out.println(res);
//Loop Checker
int i = 1;
System.out.println("In the History Loop " + i);
i++;
}
System.out.println("In the loop!");
}
stmt.close();
result.close();
con.commit();
System.out.println("After Loop and close");
}
catch (SQLException err)
{
System.out.print(err.getMessage());
}
}
You've probably got an SQL injection problem, and the t mentioned in your error is coming from something like
INSERT INTO .....'Can't Tolerate X'
^---

Resources