Search for record in database "Java.lang.NullPointerExepton" - java

I want to search for the id of a movie in a table of the database. I'm new to database connection and new to java as well. This code doesn't have error in my form but I created a record of id '1' and always gives me this error "Java.lang.NullPointerExepton".
I have the record with that id but always have that error. Any help will be appreciated
Connection conn = null;
ResultSet rs = null;
PreparedStatement pst = null;
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
String url = "jdbc:mysql://localhost:3306/project";
String userid = "root";
String password = "";
try{
String sql="SELECT Movie_idMovie FROM rental_movie"
+ "WHERE Movie_idMovie =?";
pst=conn.prepareStatement(sql);
pst.setString(1, jTextField1.getText());
rs=pst.executeQuery();
if(rs.next()){
String add1=rs.getString("Movie_idMovie");
jTextField2.setText(add1);
}
}
catch(Exception e){
JOptionPane.showMessageDialog(null,e);
}
}

The problem here is this:
Connection conn = null;
String url = "jdbc:mysql://localhost:3306/project";
String userid = "root";
String password = "";
pst=conn.prepareStatement(sql);
You missed the important step of actually opening the connection, leaving conn null when you try and use it. Try adding the following, before you call conn.prepare...
conn = DriverManager.getConnection(url, userid, password);

Related

ClassNotFoundException: net.sourceforge.jtds.jdbc.Driver Error on Android Studio

I am using Android Studio to make program.I tried to connect to database of SQL Server 2014. But I found net.sourceforge.jtds.jdbc.Driver error. I do not know where I was missing or wrong
This is my code
private static final String LOG = "DEBUG";
private static String ip = "192.168.3.85";
private static String port = "1434";
private static String Driver = "net.sourceforge.jtds.jdbc.Driver";
private static String db = "Work";
private static String un = "zom";
private static String password = "111111";
public void connect() {
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
String ConnURL = null;
String query;
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
try {
Class.forName(Driver);
ConnURL = "jdbc:jtds:sqlserver://" + ip +":"+port+";"
+ "databaseName=" + db + ";user=" + un + ";password="
+ password + ";";
query=" SELECT [Production order] FROM TIMEDATA1 WHERE RecordID = (SELECT MAX (RECORDID ) FROM TIMEDATA1 WHERE [Resource] = ? )";
conn = DriverManager.getConnection(ConnURL);
stmt=conn.prepareStatement(query);
stmt.setString(1,"M-MP3");
rs = stmt.executeQuery();
while (rs.next()) {
String result = rs.getString(1);
mTextMessage.setText(result);
Log.d("My Custom Tag", result);
}
rs.close();
stmt.close();
} catch (SQLException e) {
Log.d("Error 1", e.getMessage());
} catch (ClassNotFoundException e) {
Log.d("Error 2", e.getMessage());
}
}

MySQL connection doesn't work in Android without specific error

I have this problem when I try to connect to my MySQL database. It gives me out that it's wrong and I don't know why because it doesn't give me a specific error.
It just gives me out what I wrote in the catch.
BTW I'm using MySQL Connector/J Version 5.1.47.
This is the connection Code:
private class GetData extends AsyncTask<String,String,String> {
String msg = "";
//JDBC driver name and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://" +
DbStrings.DATABASE_URL + "/" +
DbStrings.DATABASE_NAME;
#Override
protected void onPreExecute() {
ProgressTextView.setText("Connecting to Database...");
}
#Override
protected String doInBackground(String... params) {
Connection conn = null;
Statement stmt = null;
try {
Class.forName(JDBC_DRIVER);
conn = DriverManager.getConnection(DB_URL, DbStrings.USERNAME, DbStrings.PASSWORD);
stmt = conn.createStatement();
String sql = "SELECT * FROM zimmerstamm";
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
String Bemerkung = rs.getString("Bemerkung");
Double Zimmer = rs.getDouble("Zimmer");
fruitsMap.put(Bemerkung, Zimmer);
}
msg = "Process complete";
rs.close();
stmt.close();
conn.close();
} catch (SQLException connError) {
msg = "An exception was thrwon for JDBC.";
connError.printStackTrace();
} catch (ClassNotFoundException e) {
msg = "And exception was No class found.";
e.printStackTrace();
}

How to insert image to mysql database in netbeans java

I have poor knowledge about programming. I need to save image in MySQL database. I have created a database table and there is a column to add image with longblob data type.
I have code to a button to choose image from folder in PC then it load to a jlable. Now I need to insert this image to a database.
This is my code;
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
JFileChooser fc=new JFileChooser();
fc.showOpenDialog(this);
File f=fc.getSelectedFile();
String path=f.getAbsolutePath();
jLabel1.setIcon(new ImageIcon(path));
try{
FileInputStream fin=new FileInputStream(f);
int len=(int)f.length(); Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:my­sql://localhost/hss", "root", "bis123");
PreparedStatement ps=con.prepareStatement("Insert into profile values(?)");
ps.setBinaryStream(1, fin, len);
int status=ps.executeUpdate();
if(status > 0) {
jLabel2.setText("Successfully inserted in DB");
}else{
jLabel2.setText("Image not inserted!");
}
}catch(Exception e){
System.out.println(e);
}
}
In MySQL when we use the blob type to store the data , it support only 5 kb image capacity.
CREATE TABLE image (
id varchar(45) DEFAULT NULL,
size int(11) DEFAULT NULL,
image longblob
);
created database table in above code
this is java code to insert image in database
import java.sql.*;
import java.io.*;
public class InsertImagesMysql{
public static void main(String[] args){
System.out.println("Insert Image Example!");
String driverName = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/";
String dbName = "test";
String userName = "root";
String password = "root";
Connection con = null;
try{
Class.forName(driverName);
con = DriverManager.getConnection(url+dbName,userName,password);
Statement st = con.createStatement();
File imgfile = new File("pic.jpg");
FileInputStream fin = new FileInputStream(imgfile);
PreparedStatement pre =
con.prepareStatement("insert into Image values(?,?,?)");
pre.setString(1,"test");
pre.setInt(2,3);
pre.setBinaryStream(3,(InputStream)fin,(int)imgfile.length());
pre.executeUpdate();
System.out.println("Successfully inserted the file into the database!");
pre.close();
con.close();
}catch (Exception e1){
System.out.println(e1.getMessage());
}
}
}
here is code to retrieve data from database
import java.io.*;
import java.sql.*;
public class RetriveImagesMysql{
public static void main(String[] args){
System.out.println("Retrive Image Example!");
String driverName = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/";
String dbName = "test";
String userName = "root";
String password = "root";
Connection con = null;
try{
Class.forName(driverName);
con = DriverManager.getConnection(url+dbName,userName,password);
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("select image from image");
int i = 0;
while (rs.next()) {
InputStream in = rs.getBinaryStream(1);
OutputStream f = new FileOutputStream(new File("test"+i+".jpg"));
i++;
int c = 0;
while ((c = in.read()) > -1) {
f.write(c);
}
f.close();
in.close();
}
}catch(Exception ex){
System.out.println(ex.getMessage());
}
}
}
here just assign fin to jbutton action event it will trigger automatically the run of the code

ClassNotFoundException java

I have a doubt about Class Not Found Exception. I've added all the jars in my file but I cant seem to make it work. I've added the mysql-connector.jar in my project. DOes anyone know how to make it right?
try {
String driverName = "com.mysql.jdbc.Driver";
Class.forName(driverName);
String serverName = "localhost";
String mydatabase = "UFRJSocial";
String url = "jdbc:mysql://" + serverName + "/" + mydatabase;
String username = "root";
String password = "";
connection = DriverManager.getConnection(url, username, password);
if (connection != null) {
status = ("STATUS--->Connected!");
} else {
status = ("STATUS--->The connection failed");
}
return connection;
} catch (ClassNotFoundException e) {
System.out.println("The specified driver was nor found");
//THIS IS THE LINE THAT MY CONSOLE IS SHOWING
return null;
} catch (SQLException e) {
System.out.println("it was not possible to connect to the database.");
return null;
}
Take a look at this code please:
enter code
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import app.dao.connector.DatabaseManager;
public class MySQLDatabaseManager implements DatabaseManager{
#Override
public Connection getConnection() {
final String USER_NAME ="root";
final String PASSWORD = "1234";
final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
final String JDBC_URL = "jdbc:mysql://localhost:3306/inventory system";
Connection conn = null;
try{
Class.forName(JDBC_DRIVER);
conn = DriverManager.getConnection(JDBC_URL, USER_NAME, PASSWORD);
}catch(ClassNotFoundException e){
e.printStackTrace();
}catch(SQLException e){
e.printStackTrace();
}
return conn;
}
As You can see, I tried to declare all my variables outside the try and catch block. In declaring the JDBC_URL specify your database.
I've managed to make it work. It was missing the mysql.jar file in the Web-INF folder.

Retrieve an Image stored as BLOB on a MYSQL DB

I'm trying to create a PDF based on the information that resides on a database. Know I need to retrieve a TIFF image that is stored as a BLOB on a mysql database from Java. And I don't know how to do it. The examples I've found shows how to retrieve it and save it as a File (but on disk) and I needed to reside on memory.
Table name: IMAGENES_REGISTROS
BLOB Field name: IMAGEN
Any Ideas?
On your ResultSet call:
Blob imageBlob = resultSet.getBlob(yourBlobColumnIndex);
InputStream binaryStream = imageBlob.getBinaryStream(0, imageBlob.length());
Alternatively, you can call:
byte[] imageBytes = imageBlob.getBytes(1, (int) imageBlob.length());
As BalusC noted in his comment, you'd better use:
InputStream binaryStream = resultSet.getBinaryStream(yourBlobColumnIndex);
And then the code depends on how you are going to read and embed the image.
imagebytes = rs.getBytes("images");
image=getToolkit().createImage(imageBytes);
Image img = image.getScaledInstance(100,100,Image.SCALE_SMOOTH);
ImageIcon icon=new ImageIcon(img);
jLabel6.setIcon(icon);
Try this code to get adjustable image from blog Mysql in netbeans
final String dbURL = "jdbc:mysql://localhost:3306/portfolio";
final String dbUser = "root";
final String dbPass = "";
Connection conn = null;
Statement stmt = null;
try {
//DriverManager.registerDriver(new com.mysql.jdbc.Driver());
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(dbURL, dbUser, dbPass);
System.out.println("db connected");
stmt = (Statement) conn.createStatement();
ResultSet rs1;
rs1 = stmt.executeQuery("select profileImage from tbl_welcome where id = 1117");
if (rs1.next()) {
byte[] imgData = rs1.getBytes("profileImage");//Here....... r1.getBytes() extract byte data from resultSet
System.out.println(imgData);
response.setHeader("expires", "0");
response.setContentType("image/jpg");
OutputStream os = response.getOutputStream(); // output with the help of outputStream
os.write(imgData);
os.flush();
os.close();
}
} catch (SQLException ex) {
// String message = "ERROR: " + ex.getMessage();
ex.printStackTrace();
} finally {
if (conn != null) {
// closes the database connection
try {
conn.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
}
private void loadFileDataBlobFromDataBase()
{
List<Blob> bFile = jdbcTemplate.query(sql, new RowMapper<Blob>() {
#Override
public Blob mapRow(ResultSet rs, int rowNum)
throws SQLException {
return rs.getBlob(1);
}
});
if (bFile != null && bFile.size() > 0) {
bufReader = new BufferedReader(new InputStreamReader(bFile.get(
0).getBinaryStream()));
}
if (null != bufReader) {
dataVO record = null;
String lineStr = bufReader.readLine();
record = (dataVO) lineMapper.mapLine(lineStr, 1);
}
}
}

Categories