Cannot Insert Binary values into SQL Server 2008 - sql-server

I am inserting an image file and a sound file in one button click. I am calling two stored procedures for the task. But the problem is first the image is getting saved in the database and then the sound file is overwriting it. The sound file is not getting saved in the cell allocated for it.
The two stored procedures are:
ALTER PROCEDURE [dbo].[InsertImageIntoServiceRequest]
(#ServiceRequestID int,
#FileName nvarchar(150),
#Image varbinary(max))
AS
BEGIN
update ServiceRequest
set ImageFilename=#FileName, [Image]=#Image
where ID=#ServiceRequestID
END
and
ALTER PROCEDURE [dbo].[InsertSoundIntoServiceRequest]
(#ServiceRequestID int,
#FileName nvarchar(150),
#Sound varbinary(max))
AS
BEGIN
update ServiceRequest
set SoundFilename=#FileName, Sound=#Sound
where ID=#ServiceRequestID
END
When I debugged my ASP.net application I found that while saving the sound file the InsertImageIntoServiceRequest is also getting called and the sound file is overlapping the image file.
Please suggest something.

#Saksham
I have written 3 methods: one for each for inserting image and sound and one for calling these two methods.
[System.ComponentModel.DataObjectMethodAttribute
(System.ComponentModel.DataObjectMethodType.Insert, false)]
public bool InsertImage(int ServiceRequestID, string Filename, byte[] image)
{
try
{
int i = Adapter.InsertImageIntoServiceRequest(ServiceRequestID, Filename, image);
if (i > 0)
return true;
return false;
}
catch
{
return false;
}
}
and
[System.ComponentModel.DataObjectMethodAttribute
(System.ComponentModel.DataObjectMethodType.Insert, false)]
public bool InsertSound(int ServiceRequestID, string Filename, byte[] sound)
{
try
{
string file = Filename.Replace(' ', '_');
int i = Adapter.InsertImageIntoServiceRequest(ServiceRequestID, file, sound);
if (i > 0)
return true;
return false;
}
catch
{
return false;
}
}
These two methods are called here:
[System.ComponentModel.DataObjectMethodAttribute
(System.ComponentModel.DataObjectMethodType.Insert, true)]
public int CreateServiceRequest(string Username,string EMail,string CenterIPIN,int ServiceType,int ServiceStatus,string Notes, DataTable image, DataTable sound)
{
int rowsAffected;
try
{
rowsAffected =(int)Adapter.CreateServiceRequest(Username, EMail, CenterIPIN, ServiceType, ServiceStatus, Notes);
ServiceRequestBLL srb = new ServiceRequestBLL();
if (image != null)
{
foreach (DataRow dr in image.Rows)
{
srb.InsertImage(rowsAffected, dr["Filename"].ToString(), (byte[])dr["Image"]);
}
}
if (sound != null)
{
foreach (DataRow dr1 in sound.Rows)
{
try
{
srb.InsertSound(rowsAffected, dr1["Filename"].ToString(), (byte[])dr1["Sound"]);
}
catch (Exception ex)
{
rowsAffected = 0;
}
}
}
}
catch
{
rowsAffected = 0;
}
return rowsAffected = 1;
}

Related

Retrieve data return "" in ResultSet. SQL SERVER + ANDROID STUDIO

urlImage always show "", not error and not null
#Override
protected String doInBackground(String... strings) {
try
{
Connection conn = connPO.CONN(); //Connection Object
if (conn == null)
{
}
else {
// Change below query according to your own database.
String query = "select * from config";
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(query);
if (rs != null)
{
try {
urlImage = rs.getString("url"); //--here I try get data
} catch (Exception ex) {
ex.printStackTrace();
}
msg = "TEST = "+urlImage;
} else {
msg = "No Data found!";
}
}
} catch (Exception e)
{
e.printStackTrace();
Writer writer = new StringWriter();
e.printStackTrace(new PrintWriter(writer));
msg = writer.toString();
}
return msg;
}
E/MSG===>: TEST =
urlImage = rs.getString("url") //-- why this are "" ?
propertiy url there is in database with value.
You need to call rs.next() before trying to get data from the ResultSet. The first call will move the result set cursor to the first row.
From Java Se:
boolean next()
throws SQLException
Moves the cursor froward one row from its current position. A ResultSet cursor is initially positioned before the first row; the first call to the method next makes the first row the current row; the second call makes the second row the current row, and so on.

Retrieve Image from SQLITE DB and open it in imageView using JFXbutton

I'm trying to create desktop App (scenebuilder) and I want to retrieve path of Image from DATABASE (SQLITE) and Attach it to button to open it in ImageView but I'm facing a problem while doing that.
Note: I'm trying to learn Java
My code
#FXML
private ImageView imageView;
#FXML
void btn10 (ActionEvent event) {
Connection c = null;
Statement stmt = null;
try {
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:sogeclair.sqlite");
c.setAutoCommit(false);
System.out.println("Opened database successfully");
stmt = c.createStatement();
String sql = "SELECT * FROM image WHERE rowid = 1" ;
System.out.println(sql);
ResultSet rs = stmt.executeQuery( sql );
while ( rs.next() ) {
String path=rs.getString("imaging");
imageView.setImage(new Image(path));
System.out.println();
}
rs.close();
stmt.close();
c.close();
} catch ( Exception e ) {
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
System.exit(0);
}
System.out.println("Operation done successfully");
}
and I got this in result
Opened database successfully
SELECT * FROM image WHERE rowid = 1
java.lang.IllegalArgumentException: Invalid URL: Invalid URL or resource not found
Deleting directory C:\Users\Lenovo\Documents\NetBeansProjects\sogece\dist\run538077077
jfxsa-run:
BUILD SUCCESSFUL (total time: 10 seconds)
and MyDatabase
All comments are welcome :D help me please :D
This is code from a program I wrote that retrieves an image blob from sqlite. You can download and run the program from here. It's running, but it's an incomplete program.
In your code, once you get the image using ideas from my code then just use that image to set your ImageView.
String sqlTCNote = "SELECT * FROM Company;";
try (Connection conn = DriverManager.getConnection("jdbc:sqlite:contactFX.db");
Statement stmt = conn.createStatement();
ResultSet rset = stmt.executeQuery(sqlTCNote))
{
while(rset.next())
{
Company c1 = new Company();
c1.setName(rset.getString("company_name"));
c1.setShortName(rset.getString("short_name"));
c1.setStreet(rset.getString("street"));
c1.setCity(rset.getString("city"));
c1.setState(rset.getString("state"));
c1.setZip(rset.getString("zip"));
c1.setPhoneNumber(rset.getString("phone_number"));
c1.setTollFreeNumber(rset.getString("toll_free_number"));
c1.setEmailAddress(rset.getString("email_address"));
c1.setMissionStatement(rset.getString("mission_statement"));
c1.setPersonalNote(rset.getString("personal_note"));
c1.setWebSiteAddress(rset.getString("website_address"));
//This is the part you are interested in!
InputStream input = rset.getBinaryStream("image");
InputStreamReader inputReader = new InputStreamReader(input);
if(inputReader.ready())
{
File tempFile = new File("tempFile.jpg");
FileOutputStream fos = new FileOutputStream(tempFile);
byte[] buffer = new byte[1024];
while(input.read(buffer) > 0){
fos.write(buffer);
}
Image image = new Image(tempFile.toURI().toURL().toString());
c1.setImage(image);
}
for(int i = 0; i < 10; i++)
{
c1.addEmployee(new Employee());
}
companyData.add(c1);
}
}
catch(SQLException ex)
{
Logger.getLogger(MainController.class.getName()).log(Level.SEVERE, null, ex);
}
catch (IOException ex)
{
Logger.getLogger(MainController.class.getName()).log(Level.SEVERE, null, ex);
}

how do I send datagridview data to sql server?

I tried to send datagridview data to sql server. I have logic layer and a data layer
// calling logic layer
RecLogic.ProcessRecoveryData(dataGridView1.DataSource)
then i access that datasource from datalayer
//this is my logic class
public void ProcessRecoveryData(object dataSource)
{
try
{
new RecoveryData().ProcessRecoveryData(dataSource);
}
catch (SqlException sqlEx)
{
throw sqlEx;
}
catch (Exception ex)
{
throw ex;
}
hen i access that datasource from logic layer
//this is my data class
public void ProcessRecoveryData(object dataSource)
{
try
{
sqlCon.Open();
sqlCmd.Connection = sqlCon;
SqlDataAdapter sqlAdp = new SqlDataAdapter();
for (int i = 0; i < dataGridView1.dataSource.Rows.Count; i++)
{
sqlCmd.CommandType = CommandType.StoredProcedure;
sqlCmd.CommandText = "my_sp"; sqlCmd.Parameters.AddWithValue("#p1",dataGridView1.dataSource.Rows[i].Cells["text"].Value); sqlCmd.Parameters.AddWithValue("#p2",dataGridView1.dataSource.Rows[i].Cells["text"].Value);
sqlAdp.SelectCommand = sqlCmd;
}
}
catch (SqlException sqlEx)
{
throw sqlEx;
}
catch (Exception ex)
{
throw ex;
}
finally
{
sqlCon.Close();
sqlCmd.Dispose();
}
}
how can i send datasource in data layer to sql?
You need to define a Table type and have a parameter of that type in your stored procedure......
eg
In SQL....
CREATE TYPE myTableType AS table (
categoryBridgeId uniqueIdentifier,
denomination int,
qty int
);
CREATE PROCEDURE [dbo].[My_Sproc] (#items myTableType READONLY,
etc
Then in C# you can pass a DataTable to the storred procedure...
..
var tblParam = new SqlParameter("#items", SqlDbType.Structured);
tblParam.Value = GetItemsAsDataTable(req);
tblParam.TypeName = "dbo.myTableType ";
cmd.Parameters.Add(tblParam);
...
private static DataTable GetItemsAsDataTable(ECodeAddItemsToBasketRequest req)
{
var result = new DataTable();
result.Columns.Add("categoryBridgeId", typeof(Guid));
result.Columns.Add("denomination", typeof(int));
result.Columns.Add("qty", typeof(int));
foreach (var item in req.ps)
{
Guid category = item.cid;
int denomination = item.d;
int qty = item.q;
result.Rows.Add(category, denomination, qty);
}
return result;
}
Hope this helps - Good luck!

Enum switch in Java

I have this Java class where I am writing the code for applying the overrides. I want to know if using ENUM is appropriate or if I need to use the switch case, how can I use it? Also, I have the for loop that I need to use as a common block of code for each override type. Apart from that, I do have few separate fields that I need to code for each override type.
public class EWFMService
{
private WorkbrainSystemAccessService wsa = new WorkbrainSystemAccessService();
private static final org.apache.log4j.Logger logger = org.apache.log4j.Logger.getLogger(EWFMService.class);
private final static String ovrCalcGrp = "ovrCalcGrp";
private DBConnection conn = null;
private int empId;
private Date ovrDate;
private String ovrTime;
private String ovrAction;
public List<EWFMServiceData> getProcessEWFMOverrides(String userName, String password, List<EWFMServiceInputData> inputData)
throws WSApplicationException{
logger.debug("EWFM Service");
wsa.logOn(userName, password);
List<EWFMServiceData> returnList = new ArrayList<EWFMServiceData> ();
logger.debug("userName = " + userName);
DBConnection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try{
conn = new DBConnection(ConnectionManager.getConnection());
for (int i = 0; i < inputData.size(); i++)
{
Here I want to retrieve the emp_id from the database, store the value in a variable and be able to use the variable in the rest of my program. How do I do it? To retrieve the emp_id, I am using the following query.
conn = new DBConnection(ConnectionManager.getConnection());
String sql = "SELECT EMP_ID FROM EMPLOYEE_HISTORY"
+ " WHERE EMP_VAL2 = **This is where I want to use the variable in which the values of emp_id will be stored. There can be more than 100 emp_ids**"
+ " AND SYSDATE BETWEEN EMPHIST_START_DATE AND EMPHIST_END_DATE";
EWFMServiceInputData inData = (EWFMServiceInputData) inputData.get(i);
OverrideType ot = OverrideType.getOverrideType(inData.getRecordType());
logger.debug("override type = " + ot.toString());
logger.debug("inputData ["+i+"] = " + inData.toString());
OverrideAccess oa = new OverrideAccess(conn);
OverrideData ovr = new OverrideData();
ovr.setOvrUdf4(inData.getReferenceId().toString());
if (ovrAction.equals("APPLY")) {
ovr.setOvrStatus(OverrideData.PENDING);
Here I want to determine the Action. If it is Apply, then I need to find out the recordType. So basically branch it out for each recordType using if else statements or enum as I believe switch doesn't support Java 1.5 which is what I am using. Then for each recordType, I branch out and write the appropriate code corresponding to that recordType. If Action is CANCEL, then I just write the following code.
} else if (ovrAction.equals("CANCEL")) {
String sql = "SELECT * FROM OVERRIDE"
+ " WHERE OVR_UDF4 = ?"
+ " AND OVRTYP_ID = ?";
ps = conn.prepareStatement(sql);
rs = ps.executeQuery();
while (rs.next()); {
ovr.assignByName(rs);
ovr.setUpdated(false);
ovr.setRetrieved(true);
ovr.setOvrStatus(OverrideData.CANCEL);
oa.save(ovr);
}
}
ovr.setEmpId(empId);
String strOvrDate = inData.getOvrStartDate();
ovr.setOvrStartDate(DateHelper.parseDate(strOvrDate, "MM/dd/yyyy"));
if (ovrStartTime != null) {
ovr.setOvrStartTime(ovrTime);
}
Object ovrEndDate;
if (ovrEndDate != null) {
ovr.setOvrEndDate(ovrDate);
}
Object ovrEndTime;
if (ovrEndTime!= null) {
ovr.setOvrEndTime(ovrTime);
}
ovr.setOvrComment(inData.getOvrComments());
ovr.setWbuName(inData.getWbuName());
ovr.setWbuNameActual(inData.getWbuNameActual());
ovr.setOvrNewValue("VAC");
ovr.setOvrCreateDate(new Date());
ovr.setOvrtypId(103);
oa.insert(ovr);
RuleEngine.runCalcGroup(conn,
empId,
ovrDate,
ovrDate);
//COMMON BLOCK ENDS HERE
EWFMServiceData outData = new EWFMServiceData();
outData.setReferenceId(inData.getReferenceId());
String [] status = {"SUCCESS", "ERROR", "LOCKED", "EXCEPTION"};
Random ran = new Random();
String gen = status[ran.nextInt(status.length)];
logger.debug("Status is" + status );
outData.setStatus(gen);
if (gen.equals("SUCCESS")){
outData.setErrorDetails("");
} else if (gen.equals("ERROR")) {
outData.setErrorDetails("Usage of time code VAC is not allowed; balance is insufficient." + " error");
} else if (gen.equals("LOCKED")) {
outData.setErrorDetails("Timesheet cannot be edited because it is locked for payroll close." + "locked");
} else if (gen.equals("EXCEPTION")) {
outData.setErrorDetails("{ML}QR_INCORRECT_CONDITION_PARAMETER{/ML}Error in condition AWA Is Self Override Condition: java.lang.NullPointerException{ARGS}AWA Is Self Override Conditionjava.lang.NullPointerException{/ARGS" + "exception");
}
returnList.add(outData);
}
}catch (Exception e){
logger.error("Error occured",e);
throw new WSApplicationException("Error retrieved",e);
}finally{
SQLUtil.cleanUp(conn, ps, rs);
}
wsa.logOff();
logger.debug("inputData+ ");
return returnList;
}
// I need to know if writing enum is okay or can I just write a switch case above in the for loop and branch each override type and declare their individual variables there? What's the best way? Can someone help me with the code?
public enum OverrideType {
WORKDETAIL,
WORKPREMIUM,
EMPLOYEESCHEDULE,
EMPLOYEE;
public static OverrideType getOverrideType(String recordType) {
if(recordType == null) {
throw new IllegalArgumentException("Record Type cannot be null");
}
if(recordType.equals("Work Detail")) {
return WORKDETAIL;
} else if (recordType.equals("Work Premium")) {
return WORKPREMIUM;
} else if (recordType.equals("Schedule")) {
return EMPLOYEESCHEDULE;
} else if (recordType.equals("Shift Pattern")) {
return EMPLOYEE;
} else {
throw new IllegalArgumentException("Record Type cannot be" + recordType);
}
}
}
}
THE OTHER FIELDS I NEED TO INCLUDE ARE AS FOLLOWS:
FOR WORKDETAIL, I NEED TO USE TIMECODE OF FORMAT THAT IS SENT BY THE CLIENT.
FOR WORK PREMIUM, I NEED TO USE TIMECODE OF FORMAT THAT IS SENT BY THE CLIENT AND ANOTHER FIELD IS MINUTES THAT GIVES THE NUMBER OF MINUTES WHICH IS ALSO SENT BY THE CLIENT.
Generally, using enums is appropriate, especially if you have a defined set of possible types.
You can also add behavior to the enums, which could make your enum a little bit more sophisticated:
public enum OverrideType {
WORKDETAIL("Work Detail"),
WORKPREMIUM("Work Premium"),
EMPLOYEESCHEDULE("Schedule"),
EMPLOYEE("Shift Pattern");
private String identifier;
private OverrideType(String identifier){
this.identifier = identifier;
}
public static OverrideType getOverrideType(String recordType) {
if(recordType == null) {
throw new IllegalArgumentException("Record Type cannot be null");
}
for (OverrideType ot : OverrideType.values()) {
if (recordType.equals(ot.identifier)) {
return ot;
}
}
return null;
}
}
The following example shows how to use an interface in enums or an abstract method definition:
public enum OverrideType implements OverrideTypeIF {
WORKDETAIL("Work Detail") {
public int getKey() {
return 0;
}
},
WORKPREMIUM("Work Premium") {
public int getKey() {
return 0;
}
},
EMPLOYEESCHEDULE("Schedule") {
public int getKey() {
return 0;
}
},
EMPLOYEE("Shift Pattern") {
public int getKey() {
return 0;
}
public void myInterfaceMethod() {
// do type specific behavior
}
};
private String identifier;
private OverrideType(String identifier){
this.identifier = identifier;
}
public abstract int getKey();
public void myInterfaceMethod() {
// do default behavior
}
public static OverrideType getOverrideType(String recordType) {
if(recordType == null) {
throw new IllegalArgumentException("Record Type cannot be null");
}
for (OverrideType ot : OverrideType.values()) {
if (recordType.equals(ot.identifier)) {
return ot;
}
}
return null;
}
}
public interface OverrideTypeIF {
void myInterfaceMethod();
}

Executed Stored Procedure using Dapper

I am trying to execute a stored procedure using Dapper but I get two types of errors:
Error parsing column 9 (fTaxInvoiceNumber=INV0000000028PPN - String)
Object reference not set to an instance of an object
Here is the code to execute the stored procedure:
SqlConnection db = new SqlConnection(ConnectionFactory.ConnectionString("RebateSystem"));
db.Open();
try
{
var result = db.Query<PracticeRebateOrders>("GetPracticeRebateOrderByInvoiceNumber", new
{
TaxInvoiceNumber = InvoiceNumber
}, commandType: CommandType.StoredProcedure).FirstOrDefault();
db.Close();
db.Dispose();
return result;
}
catch (Exception ex)
{
throw;
}
This is my stored procedure:
ALTER PROCEDURE [dbo].[GetPracticeRebateOrderByInvoiceNumber]
#TaxInvoiceNumber NVARCHAR(20)
AS
BEGIN
SELECT TOP(1)
[fPracticeRebateOrdersID]
,[fPracticeID]
,[fPracticeUserID]
,[fCreatedDate]
,[fInvoiceInCredits]
,[fPurchaseDate]
,[fPracticeRebateOrderStatusID]
,[fRebatePaymentRunID]
,[fRebateBatchID]
,[fTaxInvoiceNumber]
FROM
[PracticeRebateSystem].[dbo].[PracticeRebateOrders]
WHERE
fTaxInvoiceNumber = #TaxInvoiceNumber
END
Not really an answer, but based on the code available in the question and in the comments I have this... which works fine and successfully...
public void SO24605346_ProcsAndStrings()
{
connection.Execute(#"create proc #GetPracticeRebateOrderByInvoiceNumber #TaxInvoiceNumber nvarchar(20) as
select #TaxInvoiceNumber as [fTaxInvoiceNumber]");
string InvoiceNumber = "INV0000000028PPN";
var result = connection.Query<PracticeRebateOrders>("#GetPracticeRebateOrderByInvoiceNumber", new
{
TaxInvoiceNumber = InvoiceNumber
}, commandType: CommandType.StoredProcedure).FirstOrDefault();
result.TaxInvoiceNumber.IsEqualTo("INV0000000028PPN");
}
class PracticeRebateOrders
{
public string fTaxInvoiceNumber;
[System.Xml.Serialization.XmlElementAttribute(Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
public string TaxInvoiceNumber { get { return fTaxInvoiceNumber; } set { fTaxInvoiceNumber = value; } }
}
I'm happy to help, but I cannot reproduce an issue. Looks fine here.

Resources