Insert
In this chapter you will learn:
Insert command
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
/*from j av a2s . c o m*/
public class Main {
public static void main(String[] args) throws Exception {
Connection conn = getConnection();
Statement st = conn.createStatement();
st.executeUpdate("create table survey (id int,name varchar(30));");
String sql = "INSERT INTO survey (id) VALUES(?)";
PreparedStatement pstmt = conn.prepareStatement(sql);
// Insert 10 rows
for (int i = 0; i < 10; i++) {
// Set the value
pstmt.setInt(1, i);
// Insert the row
pstmt.executeUpdate();
}
ResultSet rs = st.executeQuery("SELECT * FROM survey");
while (rs.next()) {
String name = rs.getString("id");
System.out.println(name);
}
rs.close();
st.close();
conn.close();
}
private static Connection getConnection() throws Exception {
Class.forName("org.hsqldb.jdbcDriver");
String url = "jdbc:hsqldb:mem:data/tutorial";
return DriverManager.getConnection(url, "sa", "");
}
}
The code above generates the following result.
Next chapter...
What you will learn in the next chapter:
Home » Java Tutorial » Statements, ResultSet, Exception, Warning