Your cart is currently empty!
Category: java Mysql
-
Khóa học miễn phí Java & MySQL – Streaming Data nhận dự án làm có lương
Java & MySQL – Streaming Data
A PreparedStatement object has the ability to use input and output streams to supply parameter data. This enables you to place entire files into database columns that can hold large values, such as CLOB and BLOB data types.
There are following methods, which can be used to stream data −
-
setAsciiStream() − This method is used to supply large ASCII values.
-
setCharacterStream() − This method is used to supply large UNICODE values.
-
setBinaryStream() − This method is used to supply large binary values.
The setXXXStream() method requires an extra parameter, the file size, besides the parameter placeholder. This parameter informs the driver how much data should be sent to the database using the stream.
This example would create a database table XML_Data and then XML content would be written into this table.
Copy and paste the following example in TestApplication.java, compile and run as follows −
import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class TestApplication { static final String DB_URL = "jdbc:mysql://localhost/TUTORIALSPOINT"; static final String USER = "guest"; static final String PASS = "guest123"; static final String QUERY = "SELECT Data FROM XML_Data WHERE id=100"; static final String INSERT_QUERY="INSERT INTO XML_Data VALUES (?,?)"; static final String CREATE_TABLE_QUERY = "CREATE TABLE XML_Data (id INTEGER, Data LONG)"; static final String DROP_TABLE_QUERY = "DROP TABLE XML_Data"; static final String XML_DATA = "<Employee><id>100</id><first>Zara</first><last>Ali</last><Salary>10000</Salary><Dob>18-08-1978</Dob></Employee>"; public static void createXMLTable(Statement stmt) throws SQLException{ System.out.println("Creating XML_Data table..." ); //Drop table first if it exists. try{ stmt.executeUpdate(DROP_TABLE_QUERY); }catch(SQLException se){ } stmt.executeUpdate(CREATE_TABLE_QUERY); } public static void main(String[] args) { // Open a connection try(Connection conn = DriverManager.getConnection(DB_URL, USER, PASS); Statement stmt = conn.createStatement(); PreparedStatement pstmt = conn.prepareStatement(INSERT_QUERY); ) { createXMLTable(stmt); ByteArrayInputStream bis = new ByteArrayInputStream(XML_DATA.getBytes()); pstmt.setInt(1,100); pstmt.setAsciiStream(2,bis,XML_DATA.getBytes().length); pstmt.execute(); //Close input stream bis.close(); ResultSet rs = stmt.executeQuery(QUERY); // Get the first row if (rs.next ()){ //Retrieve data from input stream InputStream xmlInputStream = rs.getAsciiStream (1); int c; ByteArrayOutputStream bos = new ByteArrayOutputStream(); while (( c = xmlInputStream.read ()) != -1) bos.write(c); //Print results System.out.println(bos.toString()); } // Clean-up environment rs.close(); } catch (SQLException | IOException e) { e.printStackTrace(); } } }
Now let us compile the above example as follows −
C:>javac TestApplication.java C:>
When you run TestApplication, it produces the following result −
C:>java TestApplication Creating XML_Data table... <Employee><id>100</id><first>Zara</first><last>Ali</last><Salary>10000</Salary><Dob>18-08-1978</Dob></Employee> C:>
Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc
-
Khóa học miễn phí Java & MySQL – Batch Processing nhận dự án làm có lương
Java & MySQL – Batch Processing
Batch Processing allows you to group related SQL statements into a batch and submit them with one call to the database.
When you send several SQL statements to the database at once, you reduce the amount of communication overhead, thereby improving performance.
-
JDBC drivers are not required to support this feature. You should use the DatabaseMetaData.supportsBatchUpdates() method to determine if the target database supports batch update processing. The method returns true if your JDBC driver supports this feature.
-
The addBatch() method of Statement, PreparedStatement, and CallableStatement is used to add individual statements to the batch. The executeBatch() is used to start the execution of all the statements grouped together.
-
The executeBatch() returns an array of integers, and each element of the array represents the update count for the respective update statement.
-
Just as you can add statements to a batch for processing, you can remove them with the clearBatch() method. This method removes all the statements you added with the addBatch() method. However, you cannot selectively choose which statement to remove.
Batching with Statement Object
Here is a typical sequence of steps to use Batch Processing with Statement Object −
-
Create a Statement object using either createStatement() methods.
-
Set auto-commit to false using setAutoCommit().
-
Add as many as SQL statements you like into batch using addBatch() method on created statement object.
-
Execute all the SQL statements using executeBatch() method on created statement object.
-
Finally, commit all the changes using commit() method.
Example
The following code snippet provides an example of a batch update using Statement object −
// Create statement object Statement stmt = conn.createStatement(); // Set auto-commit to false conn.setAutoCommit(false); // Create SQL statement String SQL = "INSERT INTO Employees (id, first, last, age) " + "VALUES(200,''Zia'', ''Ali'', 30)"; // Add above SQL statement in the batch. stmt.addBatch(SQL); // Create one more SQL statement String SQL = "INSERT INTO Employees (id, first, last, age) " + "VALUES(201,''Raj'', ''Kumar'', 35)"; // Add above SQL statement in the batch. stmt.addBatch(SQL); // Create one more SQL statement String SQL = "UPDATE Employees SET age = 35 " + "WHERE id = 100"; // Add above SQL statement in the batch. stmt.addBatch(SQL); // Create an int[] to hold returned values int[] count = stmt.executeBatch(); //Explicitly commit statements to apply changes conn.commit();
Batching with PrepareStatement Object
Here is a typical sequence of steps to use Batch Processing with PrepareStatement Object −
-
Create SQL statements with placeholders.
-
Create PrepareStatement object using either prepareStatement() methods.
-
Set auto-commit to false using setAutoCommit().
-
Add as many as SQL statements you like into batch using addBatch() method on created statement object.
-
Execute all the SQL statements using executeBatch() method on created statement object.
-
Finally, commit all the changes using commit() method.
The following code snippet provides an example of a batch update using PrepareStatement object −
// Create SQL statement String SQL = "INSERT INTO Employees (id, first, last, age) " + "VALUES(?, ?, ?, ?)"; // Create PrepareStatement object PreparedStatemen pstmt = conn.prepareStatement(SQL); //Set auto-commit to false conn.setAutoCommit(false); // Set the variables pstmt.setInt( 1, 400 ); pstmt.setString( 2, "Pappu" ); pstmt.setString( 3, "Singh" ); pstmt.setInt( 4, 33 ); // Add it to the batch pstmt.addBatch(); // Set the variables pstmt.setInt( 1, 401 ); pstmt.setString( 2, "Pawan" ); pstmt.setString( 3, "Singh" ); pstmt.setInt( 4, 31 ); // Add it to the batch pstmt.addBatch(); //add more batches . . . . //Create an int[] to hold returned values int[] count = stmt.executeBatch(); //Explicitly commit statements to apply changes conn.commit();
Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc