Uploaded by abhishek.abhiranjan17

20MIS0189 ABHISHEK RANJAN LAB 4 DA

advertisement
SWE1007-Programming in Java
FALL SEMESTER–2021-2022
LAB – L23+L24
Submitted by
Full Name - ABHISHEK RANJAN
Registration No:20MIS0189
Department:M.Tech(Integrated)
Specialization: SWE
SCHOOL OF INFORMATION TECHNOLOGY AND ENGINEERING
VELLORE INSTITUTE OF TECHNOLOGY
VELLORE–632014, TAMIL NADU, INDIA
Date:11-11-2021
DIGITAL ASSIGNMENT- 4
Write a Java Program to create your own Database and table and illustrate with examples the
following interfaces.
a.Statement
b.PreparedStatement
TABLE:CUST_NUM
2
102
103
1
STATEMENT:-
COMPANY
ARVIND MILLS
RAVI AND CO
RAM BROTHERS
CHARLIE AND CO
CUST_REP
30
5008
5007
20
CREDIT LIMIT
200000
50000
23000
23000
It is used for accessing your database. Statement interface cannot accept parameters and
useful when you are using static SQL statements at runtime. If you want to run SQL query
only once then this interface is preferred over PreparedStatement.
CODE
import java.sql.*;
public class table
{
public static void main(String[] ar)
{
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/System","admin1",
"admin1");
String query = "CREATE TABLE MyTable ("
+ "ID int,"
+ "FirstName varchar(30),"
+ "LastName varchar(30),"
+ "Age int )";
Statement stmt = con.createStatement();
int count = stmt.executeUpdate(query);
System.out.println("Total rows updated "+ count);
}
catch(Exception e)
{
System.out.println(e);
}
}
PREPARED STATEMENT:It is used when you want to use SQL statements many times. The PreparedStatement
interface accepts input parameters at runtime
CODE:import java.sql.*;
import java.io.*;
class PrepareSt
{
public static void main(String[] args)
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection ("jdbc:odbc:oraodbc","scott","tiger");
PreparedStatement ps = con.prepareStatement("Select * from CUSTOMERS where
CREDIT_LIMIT >= ?");
ps.setInt(1,50000);
ResultSet rs=ps.executeQuery();
// ResultSet rs = stmt.executeQuery("select * from
CUSTOMERS");
System.out.println("CUST_NUM" + "\tCOMPANY" +
"\t\tCUST_REP" + "\tCREDIT_LIMIT");
while(rs.next())
{
int no=rs.getInt(1);
String company=rs.getString(2);
int rep=rs.getInt(3);
double credit=rs.getDouble(4); System.out.println(no+"\t\t"+company+"\t"+rep+"\t\t"
+credit);
}
rs.close();
ps.close();
con.close();
}catch(Exception e)
{
e.printStackTrace();
}
}
}
Download