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'
^---
Related
Need to left join 2 data streams and the Table API throws an exception during starting the Flink app.
It is needed to calculate based on 2 different windows on a same input stream. So eventually the 2 calculated tables/steams need to be joined.
If I use "join" instead of using "left join" the start-up error disappears. Any idea how I can solve it? Is "left join" not supported?
Below is the exception:
org.apache.flink.client.program.ProgramInvocationException: The main method caused an error: Table sink 'default_catalog.default_database.Unregistered_DataStream_Sink_1' doesn't support consuming update and delete changes which is produced by node Join(joinType=[LeftOuterJoin], where=[((userId = userId0) AND (eventEpoch = eventEpoch0))], select=[userId, eventEpoch, AVG_VALUE_A, FIRST_VALUE_B, LAST_VALUE_B, FIRST_EVENTTIME, LAST_EVENTTIME, userId0, eventEpoch0], leftInputSpec=[NoUniqueKey], rightInputSpec=[NoUniqueKey])\n\tat org.apache.flink.client.program.PackagedProgram.callMainMethod(PackagedProgram.java:372)\n\tat org.apache.flink.client.program.PackagedProgram.invokeInteractiveModeForExecution(PackagedProgram.java:222)\n\tat
Below is the code snippet.
Table inputTable = tableEnv.fromDataStream(
inputStream,
Schema.newBuilder()
.columnByExpression("rowtime", "CAST(eventTime AS TIMESTAMP(3))")
.watermark("rowtime", "rowtime - INTERVAL '" + WATERMARK_DELAY_IN_SECOND + "' SECOND")
.build());
//Register the table for use in SQL queries
tableEnv.createTemporaryView("InputTable", inputTable);
Table resultTable = tableEnv.sqlQuery(
"SELECT " +
" userId," +
" eventEpoch," +
" AVG(valueA) OVER w1 AS AVG_VALUE_B" +
" FROM InputTable " +
" WINDOW w1 AS (" +
" PARTITION BY userId ORDER BY rowtime" +
" RANGE BETWEEN INTERVAL '" + INTERVAL_A + "' SECOND PRECEDING AND CURRENT ROW)"
);
Table resultTable2 = tableEnv.sqlQuery(
"SELECT " +
" FIRST_VALUE(valueB) OVER w1 AS FIRST_VALUE_B," +
" LAST_VALUE(valueB) OVER w1 AS LAST_VALUE_B," +
" FIRST_VALUE(eventEpoch) OVER w1 AS FIRST_EVENTTIME," +
" LAST_VALUE(eventEpoch) OVER w1 AS LAST_EVENTTIME," +
" userId, eventEpoch" +
" FROM InputTable" +
" WINDOW w1 AS (" +
" PARTITION BY userId ORDER BY rowtime" +
" RANGE BETWEEN INTERVAL '" + INTERVAL_B + "' SECOND PRECEDING AND CURRENT ROW)"
);
tableEnv.createTemporaryView("ResultTable1", resultTable);
tableEnv.createTemporaryView("ResultTable2", resultTable2);
Table resultTable3 = tableEnv.sqlQuery(
"SELECT ResultTable1.*," +
" ResultTable2.FIRST_VALUE_B," +
" ResultTable2.LAST_VALUE_B," +
" ResultTable2.FIRST_EVENTTIME," +
" ResultTable2.LAST_EVENTTIME" +
" FROM ResultTable1" +
" LEFT JOIN ResultTable2" +
" ON ResultTable1.userId = ResultTable2.userId" +
" AND ResultTable1.eventEpoch = ResultTable2.eventEpoch"
);
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
When I write a simple "success" or "failure" to the sql table field I do not receive this error, but when I include a verbose command output that is ~3500 characters, I get the error in the title. The sql database field is a type of text field, which is supposed to have a 2.1 billion character limit?
What am I doing wrong?
DBConnectionlib.DBClass dbWrite = new DBConnectionlib.DBClass();
dbWrite.connectionInformation = #"Server=tcp:xxxxx,1111 ;Database=xxxxx;Trusted_Connection=false;UID=xxxxx;Pwd=xxxxx;ApplicationIntent=ReadWrite;Timeout=60;MultiSubnetFailover=True";
dbWrite.tableName = "xxxxx";
string tableNameWrite = "xxxxx";
List<string> dataItems = new List<string>();
dbWrite.insertStatement = "insert into " + tableNameWrite + " (dateTime, changeMakersSamAccount, changeMakersDisplayName, " +
"changeMakersIp,changeMakersComputerName,accountBeingChangedSamAccount,accountBeingChangedDisplayName,domainControllerUsed," +
"changeDescription,fileNameUploaded,result)" +
"VALUES" +
"('" + logging_dateTime + "', '" + logging_changeMakersSamAccount + "', '" + logging_changeMakersDisplayName + "', '"
+ logging_changeMakersIp + "', '" + logging_changeMakersComputerName + "', '" + logging_accountBeingChangedSamAccount + "', '"
+ logging_accountBeingChangedDisplayName + "', '" + logging_domainControllerUsed + "', '" + logging_changeDescription + "', '"
+ logging_fileNameUploaded + "', '" + logging_result + "')";
string dbResults = dbWrite.writeToSqlDatabase();
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
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"))
);