Command text was not set for the command object - work in other places - jscript

I'm getting the above error for some reason I can't understand. I have commented out after Connect() down to disconnect and it all runs fine, so I know the problem is there somewhere. My code is:
var sixMonth = parseInt(currentDate.getMonth() - 6);
sixMonth++;
var reviewDate = year + "-" + sixMonth + "-" + day;
var d1;
var d2 = new Date(reviewDate);
var intListViewIndex9 = 0;
Connect();
var EOF = 0;
RecordSet = new ActiveXObject("ADODB.Recordset");
//set the source
RecordSet.Source = statement;
//set the conection for the record set to use
RecordSet.ActiveConnection = ObjConnection;
//Open your RecordSet (i.e. Execute the query)
RecordSet.Open;
//declare the statement
statement = "SELECT AccessDate from screens.signoff WHERE BadgeNo = '" + BadgeNo + "'";
while (RecordSetas.EOF == false){
accessDate = RecordSet.Fields("AccessDate").Value;
d1 = new Date(accessDate);
if (d1.getTime() > d2.getTime()) {
SQL("UPDATE screens.signoff SET Recertify = '1' WHERE BadgeNo = '" + BadgeNo + "'");
}
//Move to the next record in the RecordSet
intListViewIndex9 = intListViewIndex9 + 1;
RecordSet.MoveNext;
}
//Close the RecordSet
RecordSet.Close;
//Destroy the objRecordSet object variable from memory
RecordSet = {};
disconect();
I have used this structure in other places and it works absolutely fine so I'm lost as to why this isn't.
Here are the other defined bits that are called as a part of the SQL.
var ObjConnection;
function Connect(){
ObjConnection = new ActiveXObject("ADODB.Connection");
SQLlook()
ObjConnection.Open ("DSN=SQL");
}
function disconect(){
//Close the Database Connection
ObjConnection.Close;
//Destroy the objConnection object variable from memory
ObjConnection = {};
}

ADyson was right, rather than set RecordSet.source = statement and then declare it I just set the actual SQL command after (RecordSet.Source = "Select etc etc")
RescordSetas was also a typo

Related

When trying to run an insert statement in sqlite I get an error [duplicate]

From the npm docs, only visible prepared statements are for insert. Does these prepared statement work for Select, update, and delete?
I tried for select, there isn't a .each function where the rows are called back. Anyone been able to do this or have links to resources, cause I can sure as hell unable to find any.
According to the node-sqlite3 API documentation, you can use parameters in your SQL queries in several different ways:
// Directly in the function arguments.
db.run("UPDATE tbl SET name = ? WHERE id = ?", "bar", 2);
// As an array.
db.run("UPDATE tbl SET name = ? WHERE id = ?", [ "bar", 2 ]);
// As an object with named parameters.
db.run("UPDATE tbl SET name = $name WHERE id = $id", {
$id: 2,
$name: "bar"
});
Yes, prepared statements are supported.
With node-sqlite3:
var sqlite3 = require('sqlite3').verbose();
var db = new sqlite3.Database('data.db');
db.serialize(function() {
var stmt = db.prepare("INSERT INTO users VALUES (?,?)");
for (var i = 0; i < 10; i++) {
stmt.run("user " + i, "email " + i);
}
stmt.finalize();
stmt = db.prepare("SELECT * FROM users WHERE id=?");
stmt.each(userId, function(err, row) {
console.log(row.name, row.email);
}, function(err, count) {
stmt.finalize();
});
});
With better-sqlite3:
var Database = require('better-sqlite3');
var db = new Database('foobar.db', options);
var stmt = db.prepare("INSERT INTO users VALUES (?,?)");
for (var i = 0; i < 10; i++) {
stmt.run("user " + i, "email " + i);
}
var stmt = db.prepare('SELECT * FROM users WHERE id=?');
var row = stmt.get(userId);
console.log(row.name, row.email);

Load data into multiple excel sheets depending on conditions dynamically

I have a situation please help me out. I have to create multiple sheet in one excel file with different queries. Like i have to check if the particular column is null then the record against this query should be in excel file in new sheet and i have to check another column with other name if it is null or empty and then create a sheet for it and sheet should be created only if the query returns some result otherwise there should not be any empty sheet. i have 8 different columns to check .
For Example I have to execute following query which will be in source
SELECT DISTINCT AgencySourceSystemCode,SourceAgencyID,ProgramCode,PolicyNumber,EffectiveDate,AgencyName
FROM POL.vw_PolicyPremiumData
WHERE AgencyName IS NULL OR AgencyName = ''
And Sample result is
AgencySourceSystemCode SourceAgencyID
ProgramCode PolicyNumber
EffectiveDate AgencyName
GEN 1050- CAB DN17000008
2010-06-10 NULL
GEN 1050- CAB DN17000008
2011-06-10 NULL
GEN 1050- CAB DN17000008
2012-06-10 NULL
GEN 1050- CAB DN17000010
2010-06-10 NULL
GEN 1050- CAB DN17000010
2012-06-10 NULL
GEN 1050- CAB DN17000012
2010-06-22 NULL
GEN 1050- CAB DN17000012
2011-06-22 NULL
Here Agency Name is NULL like this i will have source query where Effective can be null .
I used this code snippet to create dynamic Excel file sheets .
using System;
using System.Data;
using Microsoft.SqlServer.Dts.Runtime;
using System.Windows.Forms;
using System.IO;
using System.Data.OleDb;
using System.Data.SqlClient;
namespace ST_db9b6187d17c4dc99314d6ccb6ee7b08
{
[Microsoft.SqlServer.Dts.Tasks.ScriptTask.SSISScriptTaskEntryPointAttribute]
public partial class ScriptMain : Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTARTScriptObjectModelBase
{
string query = string.Empty;
string FileName = string.Empty;
string TableName = string.Empty;
string connstring = string.Empty;
string FolderPath = string.Empty;
string where = string.Empty;
string PackageName = "Error";
int SourceId = 0;
int BatchId = 0;
int flag = 0;
public void Main()
{
string datetime = DateTime.Now.ToString("yyyyMMddHHmmss");
try
{
FolderPath = Dts.Variables["$Package::TempFolderPath"].Value.ToString();
FolderPath = FolderPath+"\\";
//if (FolderPath.LastIndexOf("\\")="\\")
//{
// FolderPath = Dts.Variables["$Package::TempFolderPath"].Value.ToString();
//}
if (File.Exists(FolderPath + PackageName + "File.XLSX"))
{
File.Delete(FolderPath + PackageName + "File.XLSX");
}
if (FolderPath.Contains(".xlsx"))
{
FolderPath = FolderPath.Trim('\\');
FolderPath = FolderPath.Remove(FolderPath.LastIndexOf('\\') + 1);
}
//USE ADO.NET Connection from SSIS Package to get data from table
string con = Dts.Connections["oledb_conn"].ConnectionString.ToString();
OleDbConnection _connection = new OleDbConnection(con);
OleDbCommand cmd = new OleDbCommand();
//Read distinct error euerries
query = "select distinct ErrorQuery, SheetName from ErrorMapping where FileType = 'PremiumFile'";
cmd.CommandType = CommandType.Text;
cmd.CommandTimeout = 0;
cmd.CommandText = query;
cmd.Connection = _connection;
_connection.Open();
DataTable dt_ErrorMapping = new DataTable();
dt_ErrorMapping.Load(cmd.ExecuteReader());
_connection.Close();
if (dt_ErrorMapping != null && dt_ErrorMapping.Rows.Count > 0)
{
foreach (DataRow dt_ErrorMapping_row in dt_ErrorMapping.Rows)
{
query = dt_ErrorMapping_row["ErrorQuery"].ToString();
cmd.CommandType = CommandType.Text;
cmd.CommandText = query;
cmd.CommandTimeout = 0;
cmd.Connection = _connection;
_connection.Open();
DataTable dt_ErrorInfo = new DataTable();
dt_ErrorInfo.Load(cmd.ExecuteReader());
_connection.Close();
if (dt_ErrorInfo != null && dt_ErrorInfo.Rows.Count > 0)
{
Error(dt_ErrorMapping_row["SheetName"].ToString());
}
}
}
Dts.TaskResult = (int)ScriptResults.Success;
}
catch (Exception exception)
{
using (StreamWriter sw = File.CreateText(Dts.Variables["$Package::TempFolderPath"].Value.ToString() + "\\" +
"Error" + datetime + ".log"))
{
sw.WriteLine("Error Message: " + exception.Message.ToString());
Dts.TaskResult = (int)ScriptResults.Failure;
}
}
}
public void ExportExcelFile(DataSet ds, string connstring, string SheetName)
{
OleDbConnection Excel_OLE_Con = new OleDbConnection();
OleDbCommand Excel_OLE_Cmd = new OleDbCommand();
//Get Header Columns
string TableColumns = "";
// Get the Column List from Data Table so can create Excel Sheet with Header
foreach (DataTable table in ds.Tables)
{
foreach (DataColumn column in table.Columns)
{
TableColumns += column + "],[";
}
}
// Replace most right comma from Columnlist
TableColumns = ("[" + TableColumns.Replace(",", " Text,").TrimEnd(','));
TableColumns = TableColumns.Remove(TableColumns.Length - 2);
//Use OLE DB Connection and Create Excel Sheet
Excel_OLE_Con.ConnectionString = connstring;
Excel_OLE_Cmd.CommandTimeout = 0;
Excel_OLE_Con.Open();
Excel_OLE_Cmd.Connection = Excel_OLE_Con;
Excel_OLE_Cmd.CommandText = "Create table [" + SheetName + "] (" + TableColumns + ")";
Excel_OLE_Cmd.ExecuteNonQuery();
Excel_OLE_Con.Close();
//Write Data to Excel Sheet from DataTable dynamically
foreach (DataTable table in ds.Tables)
{
bool firstRow = true;
String sqlCommandInsert = "";
String sqlCommandValue = "";
foreach (DataColumn dataColumn in table.Columns)
{
sqlCommandValue += dataColumn + "],[";
}
sqlCommandValue = "[" + sqlCommandValue.TrimEnd(',');
sqlCommandValue = sqlCommandValue.Remove(sqlCommandValue.Length - 2);
sqlCommandInsert = "INSERT into [" + SheetName + "] (" + sqlCommandValue + ") VALUES(";
int columnCount = table.Columns.Count;
Excel_OLE_Con.Open();
Excel_OLE_Cmd.CommandTimeout = 0;
foreach (DataRow row in table.Rows)
{
string columnvalues = "";
for (int i = 0; i < columnCount; i++)
{
int index = table.Rows.IndexOf(row);
columnvalues += "'" + table.Rows[index].ItemArray[i].ToString() + "',";
}
columnvalues = columnvalues.TrimEnd(',');
var command = sqlCommandInsert + columnvalues + ")";
Excel_OLE_Cmd.CommandText = command;
Excel_OLE_Cmd.ExecuteNonQuery();
}
Excel_OLE_Con.Close();
}
}
public void Error(string ActualSheetName)
{
//USE ADO.NET Connection from SSIS Package to get data from table
string con = Dts.Connections["oledb_conn"].ConnectionString.ToString();
OleDbConnection _connection = new OleDbConnection(con);
OleDbCommand cmd = new OleDbCommand();
//drop Excel file if exists
if (!string.IsNullOrEmpty(ActualSheetName))
{
//FileType='PremiumFile'"
query = "Select ErrorQuery,SheetName,FileType from pol.ErrorMapping Where SheetName = '" + ActualSheetName + "' and FileType='PremiumFile'";
cmd.CommandType = CommandType.Text;
cmd.CommandText = query;
cmd.CommandTimeout = 0;
cmd.Connection = _connection;
_connection.Open();
DataTable dt_ErrorInfo = new DataTable();
dt_ErrorInfo.Load(cmd.ExecuteReader());
//cmd.ExecuteNonQuery();
_connection.Close();
if (dt_ErrorInfo != null && dt_ErrorInfo.Rows.Count > 0)
{
foreach (DataRow dt_ErrorInfo_row in dt_ErrorInfo.Rows)
{
query = dt_ErrorInfo_row["ErrorQuery"].ToString();
cmd.CommandType = CommandType.Text;
cmd.CommandText = query;
//cmd.CommandTimeout = 600;
cmd.Connection = _connection;
cmd.CommandTimeout = 0;
_connection.Open();
DataTable dt_Actual_data = new DataTable();
dt_Actual_data.Load(cmd.ExecuteReader());
//cmd.ExecuteNonQuery();
_connection.Close();
FileName = PackageName + dt_ErrorInfo_row["FileType"].ToString();
//TableName = "ErrorFileInfo ";
//Construct ConnectionString for Excel
connstring = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + FolderPath + FileName + ";" + "Extended Properties=\"Excel 12.0 Xml;HDR=YES;\"";
string SheetName = "";
object[] array = dt_ErrorInfo_row.ItemArray;
SheetName = array[1].ToString();
//Load Data into DataTable from SQL ServerTable
//string queryString = "SELECT * from " + TableName + " ";
//OleDbDataAdapter adapter = new OleDbDataAdapter(query, _connection);
DataSet ds = new DataSet();
ds.Tables.Add(dt_Actual_data);
//adapter.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
ExportExcelFile(ds, connstring, SheetName);
flag++;
}
}
}
}
}
#region ScriptResults declaration
/// <summary>
/// This enum provides a convenient shorthand within the scope of this class for setting the
/// result of the script.
///
/// This code was generated automatically.
/// </summary>
enum ScriptResults
{
Success = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Success,
Failure = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Failure
};
#endregion
}
}

'External table is not in the expected format.' when reading excel(.xlsx) file which is saving in 2010 format?

when i am reading excel(2010) file, "External table is not in the expected format." error occurs. i am using Oledb connection to read excel file.please provide me best solution for this issue. thank you...
string connectionstring = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filePath + ";Extended Properties='Excel 12.0;IMEX=1;HDR=YES'";
using (OleDbConnection conn = new OleDbConnection(connectionstring))
{
try
{
conn.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = conn;
System.Data.DataTable dtExcelSchema;
dtExcelSchema = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
string firstSheet = "";
int count = dtExcelSchema.Rows.Count;
conn.Close();
//Read Data from First Sheet
conn.Open();
DataTable dt = new DataTable();
var tempDataTable = (from dataRow in dtExcelSchema.AsEnumerable()
where !dataRow["TABLE_NAME"].ToString().Contains("FilterDatabase")
select dataRow).CopyToDataTable();
dt = tempDataTable;
firstSheet = dt.Rows[0]["TABLE_NAME"].ToString();
if (!firstSheet.EndsWith("$"))
{
firstSheet = dt.Rows[0]["TABLE_NAME"].ToString() + "$";
}
cmd.CommandText = "select * from [" + firstSheet + "]";
string query1 = "SELECT count(*) FROM [" + firstSheet + "]";
cmd = new OleDbCommand(query1, conn);
cmd.CommandText = query1;
if (Convert.ToInt32(cmd.ExecuteScalar()) > 0)
{
string sheetName = firstSheet.Replace(" ", "").Replace("'", "");
string query = "SELECT * FROM [" + sheetName + "]";
dtnew.TableName = firstSheet;
OleDbDataAdapter oda = new OleDbDataAdapter(query, conn);
oda.Fill(dtnew);
}
}
catch (Exception ex)
{
}
}

Error in ExecuteNonQuery command in C#, can't update database

here is the code that i have written for change password in my website in C#, but it shows the error in "ExecuteNonQuery()" command..and i cant update the database with new password... i have tried many solution for that like i have check permission in windows authentication for modify the "Database" file..
-> Code in Change.aspx.cs:
protected void Button1_Click(object sender, EventArgs e)
{
OleDbConnection conn = new OleDbConnection();
string connectionString = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\Lenovo\Desktop\PlacementCell\PlacementCell\Database.mdb";
conn = new OleDbConnection(connectionString);
conn.Open();
string str1 = "select * from Student_Login where Password ='" + TextBox1.Text + "'";
OleDbCommand cmd = new OleDbCommand(str1, conn);
OleDbDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
OleDbConnection con1 = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\Lenovo\Desktop\PlacementCell\PlacementCell\Database.mdb");
con1.Open();
string str = "UPDATE Student_Login SET Password=" + TextBox3.Text + "where Password= " + TextBox1.Text;
using (OleDbCommand cmd1 = new OleDbCommand(str, con1))
{
cmd1.ExecuteNonQuery();
}
Label1.Visible = true;
con1.Close();
}
else
{
Label3.Visible = true;
}
conn.Close();
}
...................
error image
It seems that there are a few syntax issues within your existing code, such as missing quotes around your parameter values when building your queries and concatenating your strings like the following line :
string str = "UPDATE Student_Login SET Password='" + TextBox3.Text + "' where Password= " + TextBox1.Text + "'";
A bigger issue here is that you aren't using SQL Parameterization, which can cause issues like this to occur (and lead to SQL Injection vulnerabilities). Consider the following code, which should resolve all of your previous issues and keep you protected against any injection-based nastiness:
// Create your connection
using (var conn = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\Lenovo\Desktop\PlacementCell\PlacementCell\Database.mdb"))
{
// Build your first query
var query = "SELECT * FROM Student_Login WHERE Password = #password";
// Create a command to execute your query
using (var cmd = new OleDbCommand(query, conn))
{
// Open your connection
conn.Open();
// Add your parameter (prevents SQL Injection and syntax issues)
cmd.Parameters.AddWithValue("#password", TextBox1.Text);
// Execute your query into a reader
using (var dr = cmd.ExecuteReader())
{
// Go through each row
while(dr.Read())
{
// Build an update query
var updateQuery = "UPDATE Student_LogIn SET Password = #password WHERE Password = #oldPassword";
// Build a new command to execute
using (var updateCmd = new OleDbCommand(updateQuery, conn))
{
// Set a parameter and execute
updateCmd.Parameters.AddWithValue("#password", TextBox3.Text);
updateCmd.Parameters.AddWithValue("#oldPassword", TextBox1.Text);
// Execute your query
updateCmd.ExecuteNonQuery();
Label1.Visible = true;
}
}
}
}
}
You can also try this version which doesn't rely on named parameters :
// Create your connection
using (var conn = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\Lenovo\Desktop\PlacementCell\PlacementCell\Database.mdb"))
{
// Build your first query
var query = "SELECT * FROM Student_Login WHERE Password = ?";
// Create a command to execute your query
using (var cmd = new OleDbCommand(query, conn))
{
// Open your connection
conn.Open();
// Add your parameter (prevents SQL Injection and syntax issues)
cmd.Parameters.AddWithValue("#password", TextBox1.Text);
// Execute your query into a reader
using (var dr = cmd.ExecuteReader())
{
// Go through each row
while(dr.Read())
{
// Build an update query
var updateQuery = "UPDATE Student_LogIn SET Password = ? WHERE Password = ?";
// Build a new command to execute
using (var updateCmd = new OleDbCommand(updateQuery, conn))
{
// Set a parameter and execute
updateCmd.Parameters.AddWithValue("#password", TextBox3.Text);
updateCmd.Parameters.AddWithValue("#oldPassword", TextBox1.Text);
// Execute your query
updateCmd.ExecuteNonQuery();
Label1.Visible = true;
}
}
}
}
}
Can you try once this...
updateCmd.Parameters.Add("#password", SqlDbType.VarChar);
updateCmd.Parameters["#password"].Value = TextBox3.Text;
updateCmd.Parameters.Add("#oldPassword", SqlDbType.VarChar);
updateCmd.Parameters["#oldPassword"].Value = TextBox1.Text;

retrieve data from access database

I want to retrieve a path of an image from access
DataTable myTable = new DataTable();
OleDbConnection myConnection = new OleDbConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
OleDbCommand myCommand = new OleDbCommand();
myCommand.CommandText = "SELECT ImageName AS 'ImageName', ImagePath AS 'Path' FROM [AImages] WHERE ID='" + _ID + "'";
myCommand.CommandType = CommandType.Text;
myCommand.Connection = myConnection;
OleDbDataAdapter myAdapter = new OleDbDataAdapter();
myAdapter.SelectCommand = myCommand;
myAdapter.Fill(myTable);
but in last line an error occurred like this: Data type mismatch in criteria expression.
I suspect the problem is with the way you pass an ID, maybe you can try this instead:
// note the ID=?
myCommand.CommandText = "SELECT ImageName AS 'ImageName', ImagePath AS 'Path' FROM [AImages] WHERE ID=?";
myCommand.CommandType = CommandType.Text;
// now a parameter
var pId = new OleDbParameter {Value = _ID};
myCommand.Parameters.Add(pId);
I hope this helps.

Resources