Insert Into Table


Leave a reply                     

Insert Into MySql Table in Java

Java MySql Insert

MySql Insert Table Using PreparedStatement

How to Insert Data In MySql Database Table in Java

PreparedStatement: Is used to complied once and then executed in loop to insert multiple values in database table tablename in column columnname2, columnname1 is not mentioned since it is auto_increment.

package raghuwansh.java.jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;

public class InsertTable {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		try {
			Class.forName("com.mysql.jdbc.Driver");
			Connection connection = DriverManager.getConnection(
					"jdbc:mysql://localhost:3306/databasename", "root", "");
			PreparedStatement preparedStatement = connection
					.prepareStatement("INSERT INTO tablename(columnname2) values (?)");
			// For multiple columns use columnname1, columnname2... in place of
			// columnname2
			ArrayList<String> arrayList = new ArrayList<String>();
			arrayList.add("raghuwansh");
			arrayList.add("com");
			arrayList.add("matrimony");
			arrayList.add("blog");
			arrayList.add("career");
			for (int idx = 0; idx < arrayList.size(); idx++) {
				preparedStatement.setString(1, arrayList.get(idx)); // 1 is
																	// index of
																	// columnname2
																	// in query
				preparedStatement.executeUpdate();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}
}

Leave a Reply

Your email address will not be published. Required fields are marked *


7 × = forty two