DataBase_Connection.java
USING DATABASE COONECTION AS
GLOBAL TO ALL PACKAGE:
import
java.sql.Connection;
import
java.sql.DriverManager;
import
java.sql.SQLException;
public class
DataBase_Connection
{
private static final String
USERNAME="root",PASSWORD="root",DRIVER="com.mysql.jdbc.Driver",
URL="jdbc:mysql://localhost/hotel";
public Connection ConnectionGet() throws ClassNotFoundException, SQLException
{
Class.forName((DRIVER));
Connection con=DriverManager.getConnection(URL, USERNAME,PASSWORD);
return con;
}
}
CALLING DataBase_Connection.java IN NATIVE CODE:
INSERT QUERY:
Statement stm=new
DatabaseConnection().ConnectionGet().createStatement();
stm.executeUpdate("insert into nutri(id,date)
values("+maxid+",'"+dt+"')");
UPDATE QUERY:
Statement stm=new
DatabaseConnection().ConnectionGet().createStatement();
stm.executeUpdate("update nutri set
"+colu+"='"+foodt+"' where id="+id+"");JOptionPane.showMessageDialog(rootPane, colu+".. INSERTED FOR DATE...."+dt);
SELECT QUERY:
Statement stm=new DatabaseConnection().ConnectionGet().createStatement();
ResultSet rs=stm.executeQuery("select * from nutri where id=(select max(id) from nutri)");
while(rs.next())
{
id=rs.getInt("id");
date=rs.getString("DATE").trim();
}
----------------------------------------------------------------------------------------------------
SIMPLE JDBC
CONNECTION WITHOUT SEPERATE CLASS USING MY SQL:
SIMPLE DATA INSERTION
WITH STRING STARTS WITH CHAR “-“:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public void datainsert() throws IOException
{
Date dt=new
Date();
int maxid=0;
try {
String
pattern = "dd/MM/yyyy";
String
pattern2="HH:mm:ss";
SimpleDateFormat
format = new SimpleDateFormat(pattern);
String
da=format.format(dt);
SimpleDateFormat format2 = new SimpleDateFormat(pattern2);
String
tm=format2.format(dt);
Class.forName("com.mysql.jdbc.Driver");
Connection
con=
DriverManager.getConnection("Jdbc:mysql://localhost/stat","root","root");
Statement stm=con.createStatement();
ResultSet rs=
stm.executeQuery("select max(id) from status");
while(rs.next())
{
maxid=rs.getInt(1);
}
maxid+=1;
String data=jPasswordField1.getText().trim();
if(data.startsWith("-"))
{
stm.executeUpdate("insert into status
values('"+maxid+"','"+da+"','"+tm+"','"+categ+data+"')");
//
JOptionPane.showMessageDialog(rootPane, "DATA ADDED");
jPasswordField1.setText("");
}
else
{
throw new
IOException("SYSTEM ERROR");
}
jButton1.setVisible(false);
con.close();
categ="$";
}
catch
(SQLException | IOException |ClassNotFoundException e)
{
JOptionPane.showMessageDialog(rootPane, e.getMessage());
}
}
No comments:
Post a Comment