Different images inserted from Android into database shows same value? - java

I am trying to insert image into SQL Server here is my code and it works perfectly (it inserts image into database). My problem starts after insertion and when I see the image column in database.
protected String doInBackground(String... strings) {
try {
con = connectionClass(ConnectionClass.un, ConnectionClass.pass, ConnectionClass.db, ConnectionClass.ip);
if (con == null) {
z = "No Internet Connection";
} else {
String sql = "INSERT INTO [dbo].[tblComplaint] (customerName,type,image) VALUES ('" + name.getText() + "','" + complain.getText() + "','" +encodedImage+"')";
//PreparedStatement stmt = con.prepareStatement(sql);
//stmt.executeUpdate();
Statement stmt = con.createStatement();
stmt.executeUpdate(sql);
}
} catch (Exception e) {
isSuccess = false;
z = e.getMessage();
}
return z;
}
#SuppressLint("NewApi")
public Connection connectionClass(String user, String password, String database, String server) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
Connection connection = null;
String connectionURL = null;
try {
Class.forName("net.sourceforge.jtds.jdbc.Driver");
connectionURL = "jdbc:jtds:sqlserver://" + server + "/" + database + ";user=" + user + ";password=" + password + ";";
connection = DriverManager.getConnection(connectionURL);
} catch (Exception e) {
Log.e("SQL Connection Error : ", e.getMessage());
}
return connection;
}
Problem: No matter what image I sent into database, it only inserts the same set of strings starting with: 0x2F396A2F34414151536B5A4A5267414241514141415141424141442F3467496F53554E44583142 and it goes on for a 100s lines, which I am guessing is not right. I have tried send 4-5 different images but this does not change. What am I doing wrong? Data type for image column is image, I have also tried varbinary(max) and so on.

Related

Facing "com.mysql.cj.exceptions.WrongArgumentException: Malformed database URL, failed to parse the main URL sections". java error while inserting"

public void actionPerformed(ActionEvent arg0) {
String departurecity = depcity.getText();
String depdate = dt.getText();
String arrivalcity = ac.getText();
String arrivaldate = dtar.getText();
String cabinclass = ccc.getText();
String seats = sts.getText();
String price = prc.getText();
try {
Connection connection = (Connection) DriverManager.getConnection("jdbc:mysql:‪//localhost:8080/airblue", "root", "");
java.sql.Statement st = connection.createStatement();
String query = "INSERT INTO flight values('" + departurecity + "','" + depdate + "','" + arrivalcity + "','" +
arrivaldate + "','" +cabinclass + "','" + seats +"','"+price+ "')";
Statement sta = (Statement) ((java.sql.Connection) connection).createStatement();
int x = ((java.sql.Statement) sta).executeUpdate(query);
JOptionPane.showMessageDialog(btnNewButton,
"done");
connection.close();
} catch (Exception exception) {
exception.printStackTrace();
}
}
});
Here is a little part of my connection code ,I have tried many solutions but none of them worked for me any solution to this problem?
Check your connection string, sometimes there might be a character after the semicolon in
mysql:‪//
Check your db url here and you will see for yourself: https://www.soscisurvey.de/tools/view-chars.php
Maybe type out that part by hand.

Cannot connect to MS Database with java

When attempting to open a connection to a database it fails giving me a NullPointerException. This happens when it is trying to get the connection on the con = DriverManager.getConnection(url); line. It goes from this line to the catch exception. What is the correct way?
public void openDatabase () {
url = "jdbc:odbc:student";
try{
con = DriverManager.getConnection(url);
stmt = con.createStatement();
txtOutput.setText("Database " + url + " is connected\n");
}
catch (Exception e) {
txtOutput.setText("Problems connecting to " + url + "\n");
}
}

How to add more `?` automatically in java in accordance with whatever amount of columns will be placed in the interface

I'm trying to create an api so I can use it to whatever project I need to create. I'm still new to java so I'm sorry in advance for the wrong codes. Anyways, I've got here this code that has the CRUD statements (except for Read/Retrieve).
import java.sql.*;
public class KitApiNew {
public static void main(String[] args) throws SQLException {
Connection dbConnection = null;
PreparedStatement PSInsert = null;
PreparedStatement PSUpdate = null;
PreparedStatement PSDelete = null;
PreparedStatement PSStatement = null;
String DBTable = "fruits";
String DBColumnSet = "fruit";
String DBID = "23";
String DBColumnSingle = "fruit";
String DBChoice ="insert";
String DBCS = "";
String insertTable = "INSERT INTO " + DBTable + "(" +DBColumnSet+ ")" + "VALUES" + "(?)";
String updateTable = "UPDATE " + DBTable + " SET " + DBColumnSingle + " = ?" + " WHERE id = ?";
String deleteTable = "DELETE FROM " + DBTable + " WHERE id = ?";
String statementTable = "INSERT INTO fruits(fruit) VALUES('grapes')";
try{
dbConnection = getDBConnection();
dbConnection.setAutoCommit(false);
if(DBChoice.equals("insert")){
//for insert
PSInsert = dbConnection.prepareStatement(insertTable);
PSInsert.setString(1, "Orange");
PSInsert.executeUpdate();
dbConnection.commit();
}
if(DBChoice.equals("update")){
//for update
PSUpdate = dbConnection.prepareStatement(updateTable);
PSUpdate.setString(1, "Apple");
PSUpdate.setString(2, DBID);
PSUpdate.executeUpdate();
dbConnection.commit();
}
if(DBChoice.equals("delete")){
//for delete
PSDelete = dbConnection.prepareStatement(deleteTable);
PSDelete.setString(1, DBID);
PSDelete.executeUpdate();
dbConnection.commit();
}
if(DBChoice.equals("statement")){
//for statement
PSStatement = dbConnection.prepareStatement(statementTable);
PSStatement.executeUpdate();
dbConnection.commit();
}
System.out.println("Success!");
}catch(SQLException e){
System.out.println("Error occured " + e.toString());
dbConnection.rollback();
}
finally{
if(PSInsert !=null){
PSInsert.close();
}
if(PSUpdate != null){
PSUpdate.close();
}
if(dbConnection != null){
dbConnection.close();
}
}
}
private static Connection getDBConnection(){
Connection con = null;
try{
Class.forName("com.mysql.jdbc.Driver");
}catch(ClassNotFoundException e){
System.out.println("Error 1 : " + e.getMessage());
}
try{
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/bongbong","root","");
}catch(SQLException e){
System.out.println("Error 2 : " + e.getMessage());
}
return con;
}
}
Oh by the way,
The values of the variables are currently temporary. I'll be changing them later to whatever they're going to be catching. I'm referring to these:
String DBTable = "fruits";
String DBColumnSet = "fruit";
String DBID = "23";
String DBColumnSingle = "fruit";
String DBChoice ="insert";
String DBCS = "";
and this
String statementTable = "INSERT INTO fruits(fruit) VALUES('grapes')";
Problem
What I really need help from is with the ? thing from the first code I posted after the VALUES word inside the String insertTable. I want it so that when I place a column amount in my interface then it'll add more ? in accordance with what was inputted (I also want it to add another PSInsert.setString(n, "value") with n+1 in accordance with the column amount inputted if it's possible). Can anyone tell me how to? I'm really new to java and I'm still a student studying at his best.
I want it to add those ? thing because what if I add more columns or if I use another table with more columns other than my fruits table. (I want it so that whatever I'm going to place in DBColumnSet --with columns separated by comma --will also relate to how many ? are going to be placed).
Oh by the way, it's a general api so I can't provide an interface.

Java connection to database

I have exhausted all avenues to sort out this problem, but to no avail. I have installed "SQL Management Studio 2012" and created a dummy database and methods, but I'm still getting a "null point exception pointer". Java and JDBC is set under user variables.
Here are the screen shots and code.
Static {
// standard code to open a connection and statement to SQL Server database
try {
// Create a variable for the connection string.
String connectionUrl = "jdbc:sqlserver://SQL-SERVER;"
+ "databaseName=ItunesDB;integratedSecurity=true;";
// Establish the connection.
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
con = DriverManager.getConnection(connectionUrl);
} // Handle any errors that may have occurred.
catch (SQLException sqle) {
System.out.println("Sql Exception :" + sqle.getMessage());
} catch (ClassNotFoundException e) {
System.out.println("Class Not Found Exception :" + e.getMessage());
}
}
public static String listAll() {
String output = "";
try {
stmt = con.createStatement();
ResultSet res = stmt.executeQuery("SELECT * FROM LibraryTable");
while (res.next()) { // there is a result
// the name field is the thrid one in the ResultSet
// Note that with ResultSet we count the fields starting from 1
output += res.getString(1) + " " + res.getString(2) + " - "
+ res.getString(3) + " " + res.getString(4) + " "
+ res.getString(5) + "\n";
}
} catch (Exception e) {
System.out.println(e);
return null;
}
return output;
}
public static String getName(String key) {
try {
SELECT * FROM LibraryTable WHERE key = '04'
stmt = con.createStatement();
ResultSet res = stmt.executeQuery("SELECT * FROM LibraryTable WHERE ID = '" + key + "'");
if (res.next()) { // there is a result
// the name field is the second one in the ResultSet
// Note that with ResultSet we count the fields starting from 1
return res.getString(2);
} else {
return null;
}
} catch (Exception e) {
System.out.println(e);
return null;
}`enter code here`
The database information:
Dummy Database
ID Name Artist Quantity Price Rating Playcount
What do I need to do to fix this?
Re install sql server in mixed mode . Then go to SQL Server configuration manager and checks is the TCP/Ip is enable . IF not enable it and restart the service. Then add sqljdbc jar in your project . Then try this code
Connection con = null;
try {
Class.forName(
"com.microsoft.sqlserver.jdbc.SQLServerDriver");
con = DriverManager.getConnection(
"jdbc:sqlserver://localhost:1433;"
+ "user=sa;password=HerongYang;"
+ "database=AdventureWorksLT");
}
user is always sa because it is the system administrator

Suddenly getting SQL Exceptions when using sql variables in statements

I have a SQL query, consisting of different statements (this is a simplified version, which also triggers the error) :
private static String getActiveKeyEventsSql =
"SET #report_model_id = 2; " +
"SELECT MAX(report_ts) AS report_ts " +
"FROM `pulse_data`.`key_event_reports` " +
"WHERE report_model_id = #report_model_id ";
I am trying to call that statement from inside my Java Application:
public static void main(String[] args) throws Exception {
MySQLLayer _db = new MySQLLayer();
Connection _conn = null;
try {
_conn = _db.getConnection();
PreparedStatement getActiveKeyEventsStmt = _conn.prepareStatement(getActiveKeyEventsSql);
ResultSet rs = getActiveKeyEventsStmt.executeQuery();
while (rs.next()) {
LOG.info(rs.getLong("report_ts"));
}
} catch (SQLException e) {
LOG.error("COULD NOT GET MAX REPORT.", e);
} finally {
try {
if (_conn != null && !_conn.isClosed()) {
_conn.close();
}
} catch (SQLException e) {
LOG.info("COULD NOT CLOSE CONNECTION.", e);
}
}
}
But it triggers the following error:
java.sql.SQLException: ResultSet is from UPDATE. No Data.
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1073)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:987)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:982)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:927)
at com.mysql.jdbc.ResultSetImpl.next(ResultSetImpl.java:6870)
at com.stockpulse.stockstorm.sentiment.JavaTest.main(JavaTest.java:36)
In other places of my application, this schema works just fine. When I copy this statement to the MySQL console, it works just fine.
Here is the String to init the DB:
config.setJdbcUrl(
"jdbc:mysql://" + cred.getHOST() + "/" + cred.getDB()
+ "?allowMultiQueries=true&characterEncoding=utf-8&useUnicode=true&rewriteBatchedStatements=true&relaxAutoCommit=true"
);
Why is JDBC behaving this way out of the sudden?
Try breaking your statement into
a = "SET #report_model_id = 2; ";
b = "SELECT MAX(report_ts) AS report_ts " +
"FROM `pulse_data`.`key_event_reports` " +
"WHERE report_model_id = #report_model_id ";
And do PreparedStatement.addBatch() for each.

Categories