'DATE' cannot hold values of type 'INTEGER' - date

I've set up an SQL database and used 'Date' as my column header which obviously has its own format as opposed to integer or char etc. However when I put in a date such as 2/11/2016 it gives me the error message - 'DATE' cannot hold values of type 'INTEGER'. Does anyone know what code I should be using? Here's my jsp below. All goes into DB when I remove all reference to date.
<%
int tableNum = 0;
String firstName = null;
String lastName = null;
String Address = null;
int Phone = 0;
java.sql.Date date = null;
int People = 0;
if (request.getParameter("table_num")!=null){
tableNum = Integer.parseInt(request.getParameter("table_num"));
}
if (request.getParameter("first")!=null){
firstName = request.getParameter("first");
}
if (request.getParameter("last")!=null){
lastName = request.getParameter("last");
}
if (request.getParameter("address")!=null){
Address = request.getParameter("address");
}
if (request.getParameter("phone")!=null){
Phone = Integer.parseInt(request.getParameter("phone"));
}
if (request.getParameter("date")!=null){
java.util.Date utilDate = new java.util.Date(request.getParameter("date"));
date = new java.sql.Date(utilDate.getTime());
}
if (request.getParameter("people")!=null){
People = Integer.parseInt(request.getParameter("people"));
}
if(tableNum != 0 && firstName != null && lastName != null && Address != null && Phone != 0 && date != null && People != 0){
String URL = "jdbc:derby://localhost:1527/Reservations";
String USERNAME= "johnpaul";
String PASSWORD= "purlease";
Connection myCon = null;
Statement ste = null;
PreparedStatement preparedStmt = null;
try{
Class.forName("org.apache.derby.jdbc.ClientDriver");
System.out.println("Connecting to DB...");
Connection con=DriverManager.getConnection("jdbc:derby://localhost:1527/Reservations","johnpaul", "purlease");
System.out.println("Connected successfuly");
System.out.println("Inserting records into table");
Statement st = con.createStatement();
String query = "INSERT INTO CUSTOMER_RESERVATIONS(TABLE_NUM,FIRST_NAME,LAST_NAME,ADDRESS,TELEPHONE,DATE,NUMBER_IN_PARTY)VALUES(" + tableNum + "," + "'" + firstName + "'" + "," + "'" + lastName + "'" + "," + "'" + Address + "'" + "," + Phone + "," + date + "," + People +")";
st.executeUpdate (query);
System.out.println("Records inserted");
}catch(SQLException se){
se.printStackTrace();
}catch(ClassNotFoundException se){
//Handle errors for JDBC
se.printStackTrace();
}catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}
}
%>

Related

set boolean value in sqlite android

I have column which is supposed to contain the true and false value in db. I understand that they should be in form of 0 and 1. I have an int column "status" but it always returns zero.
#Override
public void onCreate(SQLiteDatabase db) {
String create_table = "CREATE TABLE " + TABLE_NAME + "( "
+ "ID INTEGER PRIMARY KEY ,"
+ VALUE + " TEXT NOT NULL, "
+ STATUS + " INTEGER NOT NULL)";
db.execSQL(create_table);
}
public int getStatus(String _id,int status)
{
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT " + STATUS + " FROM "
+TABLE_NAME+" WHERE " + _ID +" =? " , new String[] {_id});
if(cursor.moveToFirst()){
return cursor.getInt(cursor.getColumnIndex(STATUS));
} else {
return 0;
}
}
I need to set to true in the case below but item_status returns zero everytime. I checked the db and there is NULL in the whole status column.
if (success) {
status = 1;
int item_status = db.getStatus(fetchId(),status);
Toast.makeText(this, " item_status " + item_status , Toast.LENGTH_SHORT).show();
}

Salesforce Error: Getting content from within triggers is currently not supported

I am trying to update existing code (written by someone else, and I am not a developer - just trying to help a friend out) so that it uses 'files' instead of the old 'attachments'.
The trigger is to: when the criteria is met on the Opportunity, send out an email and include a related file from the opportunity.
When I test it, I get the following error:
sendAttachments: execution of AfterUpdate caused by: System.VisualforceException: Getting content from within triggers is currently not supported. Trigger.sendAttachments: line 172, column 1
I have found with a google search that it can be resolved if you use "#future(callout=true) annotation before the method". Doesn't matter where I put this in the code - I can't get it to compile without errors. Wondering if it is because the logic is all in the trigger instead of the class?
Any help is appreciated.
Here is the code:
trigger sendAttachments on Opportunity (after update,after insert) {
for(Opportunity opp : trigger.new){
if(opp.Ready_for_Billing__c == true && opp.SenttoBilling__c == false){
Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
opp = [SELECT id, account.name,account.parent.name, bundledamt__c,SO_Number__c, IO_Number__c, OwnerId, Type, Contract_Start_Date__c, Expiration_Date__c,
Is_Insertion_Order__c, StageName, Note_to_Billing__c, Purchase_Order_Number__c,Billing_Country__c, Billing_Contact__c, Billing_Address__c, Bill_Email__c, Name FROM Opportunity WHERE Id = :opp.Id];
User u = [SELECT FirstName, LastName, Email FROM User WHERE Id = :opp.OwnerId];
Contact DC = [SELECT FirstName, LastName, Email FROM Contact WHERE LastName = :'Delivery-Invoices'];
Contact MC = [SELECT FirstName, LastName, Email FROM Contact WHERE LastName = :'Media-Invoices'];
Contact CC = [SELECT FirstName, LastName, Email FROM Contact WHERE LastName = :'CC-Invoices'];
String Name;
if (opp.Is_Insertion_Order__c == True){
Name = opp.IO_Number__c;
}
else{
Name = opp.SO_Number__c;
}
String AccName = opp.account.name;
String subject;
String repname = u.FirstName + ' ' + u.LastName;
String ordertype;
String owneremail = u.Email;
String notes = opp.Note_to_Billing__c;
String othernotes;
if( (opp.Billing_Country__c == 'India') || (opp.Billing_Country__c == 'Egypt')||(opp.Billing_Country__c == 'China')||(opp.Billing_Country__c == 'Pakistan' ) ||
(opp.Billing_Country__c == 'Indonesia') || (opp.Billing_Country__c == 'Viet Nam')||(opp.Billing_Country__c == 'Thailand')||(opp.Billing_Country__c == 'Malaysia' ) ||
(opp.Billing_Country__c == 'United Arab Emirates') || (opp.Billing_Country__c == 'Singapore')||(opp.Billing_Country__c == 'Poland')||(opp.Billing_Country__c == 'Romania' )){
othernotes = 'IMPORTANT: Note that invoice is going to a country that may withhold taxes. Refer to history'+'\r\n';
}else{
othernotes = '';
}
// create email content
if (opp.Type == null){
ordertype = 'Not Available';
}
else{
ordertype = opp.Type;
}
String contractdates;
if (opp.Contract_Start_Date__c == null){
if(opp.Expiration_Date__c == null){
contractdates = 'Not Available';
}
else{
contractdates = 'Expiration date - '+ opp.Expiration_Date__c.month()+ '/' + opp.Expiration_Date__c.day() +'/' +opp.Expiration_Date__c.year();
}
}
else{
if(opp.Expiration_Date__c == null){
contractdates = 'Start Date - ' + opp.Contract_Start_Date__c.month()+'/'+opp.Contract_Start_Date__c.day()+'/'+ opp.Contract_Start_Date__c.year();
}
else{
contractdates = opp.Contract_Start_Date__c.month()+'/'+opp.Contract_Start_Date__c.day()+'/'+ opp.Contract_Start_Date__c.year()+' - ' + opp.Expiration_Date__c.month()+'/'+opp.Expiration_Date__c.day()+'/'+opp.Expiration_Date__c.year();
}
}
subject = 'Ready for Billing: SO/IO '+Name+ ' for ' + AccName;
List<String> ccaddress;
if (CC != Null){
ccaddress = new List<String>{CC.Email, owneremail};
}
Else{
ccaddress = new List<String>{owneremail};
}
email.setSubject(subject);
String salutation = 'Hello Accounting, '+ '\r\n'+ '\r\n';
String line1 = 'A New order is ready to be billed: '+ '\r\n';
String line2;
if (opp.Is_Insertion_Order__c == False){
line2 = ' SO #: ' + Name + '\r\n';
}
else{
line2 = ' IO #: ' + Name + '\r\n';
}
String line3 = ' Account: '+AccName+ '\r\n';
String line4;
if (opp.Is_Insertion_Order__c == False){
line4 = ' Order Type (renewal/upsell/new): '+ ordertype + '\r\n';
}
else{
line4 = '\r\n';
}
String line5 = ' Contract Dates: '+ contractdates + '\r\n'+ '\r\n';
String line6 = '\r\n'+ '\r\n'+ 'Regards,' + '\r\n';
String line7 = repname + '\r\n' + '\r\n';
String body = salutation + line1 + line2 + line3 + line4+ line5;
string BillingNotes;
string BillingNotes2;
if (opp.Is_Insertion_Order__c == True){
if ( opp.Purchase_Order_Number__c != Null){
BillingNotes2 = 'Include PO#: ' + opp.Purchase_Order_Number__c + '\r\n';
}
else{
BillingNotes2 ='\r\n';
}
if( opp.Billing_Contact__c != Null) {
Contact bc = [SELECT Name FROM Contact WHERE Id = :opp.Billing_Contact__c];
BillingNotes = 'Bill To: ' + bc.Name + '\r\n';
BillingNotes = BillingNotes + ' ' + opp.Bill_Email__c + '\r\n';
if ( opp.Purchase_Order_Number__c != Null){
BillingNotes = BillingNotes2 + BillingNotes;
}
}
if( opp.Billing_Address__c != Null) {
if( opp.Billing_Contact__c != Null){
BillingNotes = BillingNotes + ' ' + opp.Billing_Address__c.replaceAll('<br>',', ') + '\r\n' + '\r\n';
}
else {
BillingNotes = 'Billing Address: ' + opp.Billing_Address__c.replaceAll('<br>',', ') + '\r\n' + '\r\n';
}
}
else{
BillingNotes = BillingNotes + '\r\n' + '\r\n';
}
}
if (opp.Note_to_Billing__c != Null){
string cleannotes = opp.Note_to_Billing__c.replaceAll('<br>','\r\n');
cleannotes = cleannotes.replaceAll('<[^>]+>',' ');
if (BillingNotes != Null){
BillingNotes = othernotes + '\r\n' + BillingNotes + cleannotes;
}
else{
BillingNotes = othernotes + '\r\n' + cleannotes;
}
body = body + 'Notes: '+ '\r\n' + BillingNotes;
}
if (opp.bundledamt__c > 0){
OpportunityLineItem[] bundledItems = [SELECT Id, Opportunityid, PricebookEntry.Name, TotalPrice, Quantity, UnitPrice, Description, Bundled__c
from OpportunityLineItem where (Bundled__c =: 'Yes' AND Opportunityid =: opp.Id) ];
body = body + '\r\n' + '\r\n' + 'Breakdown of bundled products:' + '\r\n';
for (OpportunityLineItem oli : bundledItems){
body = body + oli.Quantity.round() + ' ' + oli.PricebookEntry.Name + ' (' + oli.Description + '); Price: ' + oli.UnitPrice+ '; Total: ' + oli.TotalPrice + '\r\n';
}
}
body = body + line6+ line7;
email.setPlainTextBody(body);
if(opp.Is_Insertion_Order__c == true){
email.setToAddresses(new String[]{MC.Email});
}
else if( opp.account.parent.name == 'XXX Group' && (opp.Contract_Start_Date__c.daysBetween(opp.Expiration_Date__c))<32) {
email.setToAddresses(new String[]{MC.Email});
}
else{
email.setToAddresses(new String[]{DC.Email});
}
email.setCcAddresses(ccaddress);
List<Messaging.Emailfileattachment> fileAttachments = new List<Messaging.Emailfileattachment>();
PageReference pref = page.attachIOPDFforBilling;
/*for (Attachment a : [select Name, Body, BodyLength from Attachment where ParentId = :opp.Id]){
Messaging.Emailfileattachment efa = new Messaging.Emailfileattachment();*/
for (ContentDocumentLink a : [SELECT ContentDocumentId, LinkedEntityId FROM ContentDocumentLink where LinkedEntityId=: opp.id]){
Messaging.Emailfileattachment efa = new Messaging.Emailfileattachment();
//efa.setFileName(a.Title);
efa.setBody(pref.getContentAsPDF());
fileAttachments.add(efa);
}
email.setFileAttachments(fileAttachments);// Send email
Messaging.sendEmail(new Messaging.SingleEmailMessage[] { email });
}
}
}
Yes, it's because it's just a block of code in a trigger. It's against best practices, ideally you'd have some handler class in there with "meat" of the logic and trigger would have just few lines to call it.
If you want to change as little as possible you can still do it in 1 file. It looks absolutely crazy but you can have main code in a trigger and methods defined in it.
Take a backup of the current code and try with structure similar to this (I'm not saying it's perfect, might not compile, there might be typos. And there are performance issues like "query in a loop" (pulling info about the user that owns this opportunity - it might work fine for single records but it'll crash and burn if you mass insert ~20 opps at same time.... sorry, you might need a programmer to do it right and maybe cough up some $ for professional services look into this code and decide what's best.
trigger sendAttachments on Opportunity (after update,after insert) {
Set<Id> opportunitiesToSend = new Set<Id>();
for(Opportunity opp : trigger.new){
if(opp.Ready_for_Billing__c == true && opp.SenttoBilling__c == false){
opportunitiesToSend.add(opp.Id);
}
}
if(!opportunitiesToSend.isEmpty()){
sendEmails(opportunitiesToSend);
}
// it looks insane but it works, a method defined straight in a trigger.
// to do it properly - you should have another class you're calling
#future (callout=true)
static void sendEmails(Set<Id> opportunityIds){
Map<Id, Opportunity> opps = [SELECT id, account.name,account.parent.name,
bundledamt__c,SO_Number__c, IO_Number__c, OwnerId, Type, Contract_Start_Date__c,
Expiration_Date__c, Is_Insertion_Order__c, StageName, Note_to_Billing__c,
Purchase_Order_Number__c,Billing_Country__c, Billing_Contact__c,
Billing_Address__c, Bill_Email__c, Name
FROM Opportunity
WHERE Id IN :opportunityIds]);
for(Id i : opportunityIds){
opp = opps.get(i);
// put rest of the code here
User u = [SELECT FirstName, LastName, Email FROM User WHERE Id = :opp.OwnerId];
Contact DC = [SELECT FirstName, LastName, Email FROM Contact WHERE LastName = :'Delivery-Invoices'];
Contact MC = [SELECT FirstName, LastName, Email FROM Contact WHERE LastName = :'Media-Invoices'];
Contact CC = [SELECT FirstName, LastName, Email FROM Contact WHERE LastName = :'CC-Invoices'];
String Name;
// ...
}
}
}

How to insert same id after insert update in c#

I'm trying to create an attendance project. I'm using update & insert in my code. Please check my code below. I know I'm vulnerable to SQL injection.
My problem is when I tried to Time In using the same ID even if I use that same ID for time out, it displays the time out not time-in. Any idea how I can time in again using same ID?
MySqlCommand cmd = new MySqlCommand("SELECT * FROM tbl_student_list INNER JOIN attendance_tbl On tbl_student_list.ID = attendance_tbl.stud_id WHERE stud_id ='" + dataGridView1.Rows[i].Cells["Column1"].Value + "'", conn);
cmd.Parameters.AddWithValue("stud_id", dataGridView1.Rows[i].Cells["Column1"].Value);
conn.Open();
MySqlDataReader DataRead = cmd.ExecuteReader();
DataRead.Read();
This is my Update Code:
//If already Time-In execute Time-Out
if (DataRead.HasRows)
{
dataGridView1.Rows[i].Cells["Column3"].Value = DataRead[1].ToString();
dataGridView1.Rows[i].Cells["Column4"].Value = DataRead[2].ToString();
dataGridView1.Rows[i].Cells["Column2"].Value = DateTime.Now.ToString("yy/MM/dd");
byte[] images = ((byte[])DataRead[3]);
if (images == null)
{
pictureBox1.Image = null;
}
else
{
MemoryStream mstreem = new MemoryStream(images);
pictureBox1.Image = Image.FromStream(mstreem);
conn.Close();
conn.Open();
string sqla = "Update attendance_tbl SET TimeOut = '" + Time + "' , Name ='" + dataGridView1.Rows[i].Cells["Column3"].Value + "' where stud_id = '" + dataGridView1.Rows[i].Cells["Column1"].Value + "'";
cmd = new MySqlCommand(sqla, conn);
cmd.ExecuteNonQuery();
dataGridView1.Rows[i].Cells["Column7"].Value = DateTime.Now.ToLongTimeString();
This is My Insert Code:
//IF Not In Execute Time-In/Not exist in tbl attendance
string sqlQu = "select ID,Name,Course,Image from tbl_student_list where ID= '" + dataGridView1.Rows[i].Cells["Column1"].Value + "'";
md = new MySqlCommand(sqlQu, conn);
MySqlDataReader DataReaders = cmd.ExecuteReader();
DataReaders.Read();
if (DataReaders.HasRows)
{
dataGridView1.Rows[i].Cells["Column3"].Value = DataReaders[1].ToString();
dataGridView1.Rows[i].Cells["Column4"].Value = DataReaders[2].ToString();
dataGridView1.Rows[i].Cells["Column2"].Value = DateTime.Now.ToString("yy/MM/dd");
byte[] images = ((byte[])DataReaders[3]);
if (images == null)
{
pictureBox1.Image = null;
}
else
{
MemoryStream mstreem = new MemoryStream(images);
pictureBox1.Image = Image.FromStream(mstreem);
Purpose f2 = new Purpose();
if (f2.ShowDialog() == DialogResult.OK)
{
dataGridView1.Rows[i].Cells["Column5"].Value = f2.Rad;
}
conn.Close();
conn.Open();
string sql = "insert into attendance_tbl(stud_id,Date,Name,Course,Purpose,TimeIn)values('" + dataGridView1.Rows[i].Cells["Column1"].Value + "','" + Date + "','" + dataGridView1.Rows[i].Cells["Column3"].Value + "','" + dataGridView1.Rows[i].Cells["Column4"].Value + "','" + dataGridView1.Rows[i].Cells["Column5"].Value + "','" + Time + "')";
cmd = new MySqlCommand(sql, conn);
cmd.ExecuteNonQuery();
dataGridView1.Rows[i].Cells["Column6"].Value = DateTime.Now.ToLongTimeString();

Select results truncated without error message

I'm using Google Cloud SQL from an App Engine application via Java and JDBC.
I select rows of a table using following code:
public void processGcmRegistrations(String whereCondition, String appName,
String[] appVariants, boolean onlyTestDevices,
String orderByCondition,
GcmRegistrationProcessor processor) throws DbException {
if (whereCondition == null && appName == null)
throw new IllegalArgumentException("One of the parameters \"whereCondition\", " +
"\"appNmae\" must not be null.");
if (whereCondition == null) {
whereCondition = "APP_NAME = '" + appName + "' " +
createInListCondition("APP_VARIANT", appVariants);
if (onlyTestDevices)
whereCondition += " AND TEST_DEVICE = 1 ";
}
String orderByConditionStr = "";
if (orderByCondition != null)
orderByConditionStr = " ORDER BY " + orderByCondition;
String selectStmt = "SELECT GCM_ID, GCM_REGISTRATION_TIME, APP_NAME, APP_VARIANT, " +
"INSTALLATION_ID, DEVICE, LAST_UPDATE " +
"FROM GcmRegistration WHERE " + whereCondition + orderByConditionStr;
log.info("GcmIds Select: " + selectStmt);
ResultSet rs = null;
try {
long start = System.currentTimeMillis();
rs = dbConnection.createStatement().executeQuery(selectStmt);
log.info("Select duration: " + ((System.currentTimeMillis()-start)/1000) + " secs.");
int count = 0;
while (rs.next()) {
GcmRegistration reg = new GcmRegistration();
reg.gcmId = rs.getString(1);
reg.gcmRegistrationTime = rs.getLong(2);
reg.appName = rs.getString(3);
reg.appVariant = rs.getString(4);
reg.installationId = rs.getString(5);
reg.device = rs.getString(6);
reg.lastUpdate = rs.getLong(7);
processor.processGcmRegistration(reg);
count++;
}
log.info(count + " GcmRegistrations processed.");
} catch (Exception e) {
String errorMsg = "Selecting GCM_IDs from table GcmRegistration failed.";
log.log(Level.SEVERE, errorMsg, e);
throw new DbException(errorMsg, e);
} finally {
if (rs != null)
rs.close();
}
}
I always execute this method with the same parameters and receive usually about 152000 rows.
In rare cases (I guess 1 from 50) I receive only about 62000 rows without any exception! rs.next() returns false, although not all result rows are delivered.
For Google: Last time this happened was 8/22/14 23:20 (MEST)

excel data uploading is not working in sql database

This is pradeep
This is the code of the excel uploading to sql database
protected void btnupload_Click ( object sender, EventArgs e )
{
//string name = ddloutlet.SelectedValue.ToString ();
//cal
try
{
System.IO.FileInfo file = new System.IO.FileInfo(fileupload1.PostedFile.FileName);
string fname = file.Name.Remove((file.Name.Length - file.Extension.Length), file.Extension.Length);
fname = fname + DateTime.Now.ToString("_ddMMyyyy_HHmmss") + file.Extension;
fileupload1.PostedFile.SaveAs(Server.MapPath("locations/") + fname);
string filexetion = file.Extension;
if ( filexetion == ".xlsx" )
{
excelConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + Server.MapPath ( "locations/" ) + fname + ";" + ";Extended Properties=\"Excel 12.0;HDR=YES;\"";
}
else if ( filexetion == ".xls" )
{
excelConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + Server.MapPath ( "locations/" ) + fname + ";" + "Extended Properties=\"Excel 8.0;HDR=Yes; \"";
}
OleDbConnection connection = new OleDbConnection(excelConnectionString);
OleDbCommand command = new OleDbCommand("Select * FROM [Sheet1$]", connection);
connection.Open();
OleDbDataReader dr = command.ExecuteReader();
SqlConnection conn = new SqlConnection(strconnection);
conn.Open();
try
{
if (dr.Read() == true)
{
while (dr.Read())
{
string locationname = dr["Location Name"].ToString();
string status = dr["Status"].ToString();
if (locationname != "" && status != "")
{
string query = " select locationname from tbllocations where locationname='" + locationname + "' and outletid='" + Session["outlet_id"].ToString() + "'";
// conn.Open();
SqlCommand cmdquery = new SqlCommand(query, conn);
SqlDataReader drreader;
drreader = cmdquery.ExecuteReader();
if (drreader.Read())
{
c = true;
ssss = ssss + locationname + ",";
// ss = ssss.Split(',');
}
else
{
drreader.Close();
string qryprduct = "insert into tbllocations(locationname,status,outletid,cityid)values('" + locationname + "','" + status + "','" + Session["outlet_id"].ToString() + "','" + Session["cityid"].ToString() + "')";
SqlCommand cmd1 = new SqlCommand(qryprduct, conn);
conn.Close();
conn.Open();
cmd1.ExecuteNonQuery();
lblerror1.Visible = true;
lblerror1.Text = "Locations uploaded Sucess";
//conn.Close();
}
drreader.Close();
}
}
// connection.Close (); conn.Close ();
}
else
{
lblerror1.Text = "There is a empty excel sheet file,plz check";
lblerror1.Visible = true;
}
}
catch (Exception ex)
{
lblerror1.Visible = true;
lblerror1.Text = "Plz check the excel file formate";
}
finally
{
connection.Close(); conn.Close();
bind();
if (c == true)
{
lblerror1.Visible = true;
lblerror1.Text = "In excel this loactions are already exist. Please check,";
//for (int i = 0; i < ss.Length; i++)
//{
lblerror3.Visible = true;
lblerror3.Text = ssss;
//}
}
}
}
catch
{
}
}
The above code uploading is working but in excel 1st record is not uploading ,please tell me the what is the problem and give me suggestion please.
excel data is
Location Name Status
test1 1
test2 1
test3 1
test4 0
test5 1
test6 0
test7 1
test8 0
test9 1
test10 1
Thanks
Pradeep
You need to remove the
if (dr.Read() == true)
because it is immediately followed by a
while (dr.Read())
Each of these will read a record and the first one will skip the first row of the file