0% found this document useful (0 votes)
4 views5 pages

MySQL Java Connection and Operations

The document presents a Java class named MySQL that facilitates database operations using MySQL. It includes methods for establishing a connection, creating databases and tables, inserting data, retrieving values, and deleting records. Error handling is implemented using logging and dialog messages to inform the user of the operation results.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views5 pages

MySQL Java Connection and Operations

The document presents a Java class named MySQL that facilitates database operations using MySQL. It includes methods for establishing a connection, creating databases and tables, inserting data, retrieving values, and deleting records. Error handling is implemented using logging and dialog messages to inform the user of the operation results.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Clase MySQL

SERVIDOR CODIGO
XAMPP

APPSERV
package mysql_test;

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

public class MySQL {

private static Connection Conexion;

public void MySQLConnection(String user, String pass,


String db_name) {
try {
[Link]("[Link]");
Conexion =
[Link]("jdbc:mysql://localhost/" +
db_name, user, pass);
[Link]("Se ha iniciado la conexión con el
servidor de forma exitosa");
} catch (ClassNotFoundException ex) {

[Link]([Link]()).log([Link],
null, ex);
} catch (SQLException ex) {

[Link]([Link]()).log([Link],
null, ex);
}
}

public void closeConnection() {


try {
[Link]();
[Link]("Se ha finalizado la conexión con
el servidor");
} catch (SQLException ex) {

[Link]([Link]()).log([Link],
null, ex);
}
}

public void createDB(String name) {


try {
String Query = "CREATE DATABASE " + name;
Statement st = [Link]();
[Link](Query);
MySQLConnection("root", "root", name);
[Link](null, "Se ha creado
la base de datos " + name + " de forma exitosa");
} catch (SQLException ex) {

[Link]([Link]()).log([Link],
null, ex);
}
}

public void createTable(String name) {


try {
String Query = "CREATE TABLE " + name + ""
+ "(ID VARCHAR(25),Nombre VARCHAR(50),
Apellido VARCHAR(50),"
+ " Edad VARCHAR(3), Sexo VARCHAR(1))";
[Link](null, "Se ha creado
la base de tabla " + name + " de forma exitosa");
Statement st = [Link]();
[Link](Query);
} catch (SQLException ex) {

[Link]([Link]()).log([Link],
null, ex);
}
}

public void insertData(String table_name, String ID, String


name, String lastname, String age, String genero) {
try {
String Query = "INSERT INTO " + table_name + "
VALUES("
+ "\"" + ID + "\", "
+ "\"" + name + "\", "
+ "\"" + lastname + "\", "
+ "\"" + age + "\", "
+ "\"" + genero + "\")";
Statement st = [Link]();
[Link](Query);
[Link](null, "Datos
almacenados de forma exitosa");
} catch (SQLException ex) {
[Link]([Link]());
[Link](null, "Error en el
almacenamiento de datos");
}
}

public void getValues(String table_name) {


try {
String Query = "SELECT * FROM " + table_name;
Statement st = [Link]();
[Link] resultSet;
resultSet = [Link](Query);

while ([Link]()) {
[Link]("ID: " +
[Link]("ID") + " "
+ "Nombre: " +
[Link]("Nombre") + " " +
[Link]("Apellido") + " "
+ "Edad: " + [Link]("Edad") + "
"
+ "Sexo: " + [Link]("Sexo"));
}

} catch (SQLException ex) {


[Link](null, "Error en la
adquisición de datos");
}
}

public void deleteRecord(String table_name, String ID) {


try {
String Query = "DELETE FROM " + table_name + "
WHERE ID = \"" + ID + "\"";
Statement st = [Link]();
[Link](Query);

} catch (SQLException ex) {


[Link]([Link]());
[Link](null, "Error
borrando el registro especificado");
}
}

Common questions

Powered by AI

A significant security vulnerability in the Java class is SQL injection risk, notably in methods like insertData and deleteRecord. These methods construct SQL queries by concatenating user input directly into the query strings, which can be exploited by malicious input to execute arbitrary SQL commands. Implementing PreparedStatement instead of Statement, thus parameterizing SQL inputs, would mitigate this vulnerability .

To terminate the connection to the MySQL database, use the closeConnection() method. This method calls the close() function on the Connection object. If the operation is successful, a message indicating the connection's closure is printed. Any SQLException encountered during the process is logged at the SEVERE level without disrupting program flow .

The MySQL class ensures SQL commands are executed by using a Statement object created from the current Connection and then calling executeUpdate() or executeQuery() with the constructed SQL command string. A potential issue is that all SQL commands are constructed by concatenating strings, which can result in syntax errors if inputs aren't validated and can lead to SQL injection vulnerabilities if user input isn't properly sanitized .

Data can be inserted into a table by using the insertData(String table_name, String ID, String name, String lastname, String age, String genero) method. This method constructs an SQL INSERT statement with the provided data values and executes it using a Statement object associated with the current Connection. Successful execution results in a message displaying successful data storage, while an exception is caught and handled if errors occur .

JOptionPane is used in the Java class to display dialog boxes directly to the user for immediate feedback on successful operations or errors, offering a GUI-based interaction. Logging, on the other hand, records messages (errors specifically) at different levels such as SEVERE for traceback and diagnostic purposes without user interaction. While JOptionPane provides direct user feedback, logging captures a detailed history of events, aiding in debugging .

Using the provided Java class, a new database can be created by calling the createDB(String name) method. It executes the SQL command 'CREATE DATABASE [name]' using a Statement object from the current Connection. After executing the update, the method establishes a connection to the newly created database to confirm success and also displays a confirmation message using JOptionPane .

To establish a connection to a MySQL server using JDBC in Java, follow these steps: 1) Load the JDBC driver by invoking Class.forName() with the driver class (org.gjt.mm.mysql.Driver). 2) Use DriverManager.getConnection() with the appropriate database URL, user, and password to obtain a Connection object. 3) Handle any ClassNotFoundException and SQLException that may occur during these processes .

The createTable(String name) method is responsible for creating a database table. The key features of the table it creates include columns for 'ID' (VARCHAR(25)), 'Nombre' (VARCHAR(50)), 'Apellido' (VARCHAR(50)), 'Edad' (VARCHAR(3)), and 'Sexo' (VARCHAR(1)). It uses an SQL CREATE TABLE command executed by a Statement object. Upon successful creation, it displays a confirmation dialog using JOptionPane .

The getValues(String table_name) method's role is to retrieve all records from a specified table. It performs this by executing an SQL SELECT query to obtain a ResultSet containing the table's data. The method iterates through the ResultSet, printing out column values ('ID', 'Nombre', 'Apellido', 'Edad', 'Sexo') for each record. If an SQLException occurs, a message dialog shows an error occurred in data acquisition .

To improve robustness in handling SQL connection closures, check if the Connection object is non-null before attempting to close it, and wrap the close operation in a try-catch block to gracefully handle potential SQLExceptions. Finally, setting the Connection object to null post-closure can prevent further operations on a closed connection. Employing these precautions ensures that connection closure failures don't lead to program instability .

You might also like