JDBC Connection
JDBC Connection
2.In MySQLJavaConnection open pom.xml file and write the following code
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>MySQLJavaConnection</groupId>
<artifactId>MySQLJavaConnection</artifactId>
<version>0.0.1-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.30</version>
</dependency>
</dependencies>
</project>
3. Now create java class name with MySQLJavaConnection and write down following code.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
}
//create
//insert
String sql="insert into Employee(EmployeeID,Name,Address,City)"
+ "values (?,?,?,?);";
PreparedStatement statement=conn.prepareStatement(sql);
statement.setInt(1,101);
statement.setString(2,"John");
statement.setString(3,"Hyderabad");
statement.setString(4,"India");
int rowsInserted=statement.executeUpdate();
if(rowsInserted >0)
{
System.out.println("A new row was inserted successfully!");
}
//Update
String sql="Update Employee set city=? where EmployeeID=?";
PreparedStatement statement=conn.prepareStatement(sql);
statement.setString(1,"Hyderabad");
statement.setInt(2,101);
int rowsUpdated=statement.executeUpdate();
if(rowsUpdated >0)
{
System.out.println("A new row was Updated successfully!");
}
//Delete
String sql="delete from Employee where EmployeeID=?";
PreparedStatement statement=conn.prepareStatement(sql);
statement.setInt(1,101);
int rowsDeleted=statement.executeUpdate();
if(rowsDeleted>0)
{
System.out.println("A row was deleted successfully!");
}
}
catch(SQLException ex)
{
System.out.println("Exception ::" +ex.getMessage());
ex.printStackTrace();
}
finally
{
conn.close();
}
}
}