Set Byte Using Prepared Statement

From Java Example Source Code

Jump to: navigation, search

Contents

[edit] Overview - Set Byte Using Prepared Statement

This Java example program shows how to set Byte using Prepared Statement.

[edit] Java Source Code

  • Package: example.jdbc.preparedstatement
  • File: DemoPreparedStatementSetBytes.java
package example.jdbc.preparedstatement;
 
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
 
public class DemoPreparedStatementSetBytes {
    public static Connection getConnection() throws Exception {
	String driver = "org.gjt.mm.mysql.Driver";
	String url = "jdbc:mysql://localhost/databaseName";
	String username = "root";
	String password = "root";
	Class.forName(driver);
	Connection conn = DriverManager.getConnection(url, username, password);
	return conn;
    }
 
    public static void main(String[] args) throws Exception {
	byte[] shortData = "www.java2s.com".getBytes();
	byte[] longData = "www.java2s.com".getBytes();
 
	Connection conn = null;
	PreparedStatement pstmt = null;
	try {
	    conn = getConnection();
	    String query = "insert into bytes_table (id, short_data, long_data) values(?, ?, ?)";
 
	    pstmt = conn.prepareStatement(query);
	    pstmt.setString(1, "0001");
	    pstmt.setBytes(2, shortData);
	    pstmt.setBytes(3, longData);
 
	    int rowCount = pstmt.executeUpdate();
	    System.out.println("rowCount=" + rowCount);
	} finally {
	    pstmt.close();
	    conn.close();
	}
    }
}

[edit] What Result You Can Get

Coming soon... Run the program, you will get:

Replace with the result of you Java program.

[edit] Required External Libraries and/or Files for this Java Example

In order to run this Java example, one of the following libraries may be required: In order to run this example program, one of the following libraries may be required:

  • MySQL JDBC driver. You can download it from MySQL Connector/J — for connecting to MySQL from Java
  • Oracle JDBC driver. You can download it from JDBC driver for Oracle.
  • MSSQL JDBC driver. There are several vendors provide JDBC driver for MSSQL, you should chose one of them:
  • PostgreSQL JDBC driver. You can download it from PostgreSQL JDBC driver. It is a pure Java (Type IV) implementation.
  • HSQLDB JDBC Driver. HSQLDB is the leading SQL relational database engine written in Java. It has a JDBC driver and supports a rich subset of ANSI-92 SQL plus SQL 99 and 2003 enhancements. You can download it from hsqldb..


[edit] How to Run this Java Example Program

We recommend running this Java example program with Eclipse.

For assistance in working with Eclipse, please see How to Run Java Program with Eclipse.

It's fairly easy.



[edit] Question & Answer

Any question?

Click edit and post your question or answer here.


Personal tools