Jdbc Connection
Fri Nov 15 2024 19:01:03 GMT+0000 (Coordinated Universal Time)
Saved by
@login123
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.ResultSet;
import java.sql.Statement;
public class JdbcConnectionExample {
public static void main(String[] args)throws ClassNotFoundException {
Connection con = null;
Statement st=null;
String url = "jdbc:mysql://localhost:3306/books";
String username = "root";
String password = "ramesh";
try {
Class.forName("com.mysql.cj.jdbc.Driver");
con = DriverManager.getConnection(url, username, password);
System.out.println("Connected!");
st= con.createStatement();
System.out.println("Inserting Records into the table");
int rowupdate=st.executeUpdate("insert into book values(33,'Machine Learning through JavaScript','Anderson','Taylor series',2500)");
ResultSet rs1=st.executeQuery("Select * from book");
//Get the values of the record using while loop from result set
while(rs1.next())
{
int id = rs1.getInt(1);
String title = rs1.getString(2);
String author = rs1.getString(3);
String publisher = rs1.getString(4);
int price = rs1.getInt(5);
//String totalMarks= rs1.getInt(5);
//store the values which are retrieved using ResultSet and print them
System.out.println(id + ","+title+ ","+author+ ","+publisher +","+price );
}
} catch (SQLException ex) {
throw new Error("Error ", ex);
} finally {
try {
if (con != null) {
con.close();
}
} catch (SQLException ex) {
System.out.println(ex.getMessage());
}
}
}
}
content_copyCOPY
Comments