Descripción
La clase Connection
del paquete java.sql
es una interfaz que representa una conexión con una base de datos SQL. Esta conexión permite ejecutar sentencias SQL, gestionar transacciones y obtener información sobre la base de datos. Es el punto de entrada principal para interactuar con una base de datos desde una aplicación Java.
Sintaxis
public interface Connection extends Wrapper, AutoCloseable
Campos
- TRANSACTION_NONE
- TRANSACTION_READ_COMMITTED
- TRANSACTION_READ_UNCOMMITTED
- TRANSACTION_REPEATABLE_READ
- TRANSACTION_SERIALIZABLE
Métodos
- abort()
- beginRequest()
- clearWarnings()
- close()
- commit()
- createArrayOf()
- createBlob()
- createClob()
- createNClob()
- createSQLXML()
- createStatement()
- createStruct()
- endRequest()
- getAutoCommit()
- getCatalog()
- getClientInfo()
- getHoldability()
- getMetaData()
- getNetworkTimeout()
- getSchema()
- getTransactionIsolation()
- getTypeMap()
- getWarnings()
- isClosed()
- isReadOnly()
- isValid()
- nativeSQL()
- prepareCall()
- prepareStatement()
- releaseSavepoint()
- rollback()
- setAutoCommit()
- setCatalog()
- setClientInfo()
- setHoldability()
- setNetworkTimeout()
- setReadOnly()
- setSavepoint()
- setSchema()
- setShardingKey()
- setShardingKeyIfValid()
- setTransactionIsolation()
- setTypeMap()
Ejemplo
public class InsertarDatos {
public static void main(String[] args) {
Connection con = null;
PreparedStatement stmt = null;
String sDriver = "com.mysql.jdbc.Driver";
String sURL = "jdbc:mysql://localhost:3306/lineadecodigo";
try{
Class.forName(sDriver).newInstance();
con = DriverManager.getConnection(sURL,"root","");
String sISBN = "84-9815-212-7";
String sTitulo = "Yo, Claudio";
String sDescripcion="Supuesta autobiografía de Claudio";
String sCategoria = "Novela Histórica";
int idAutor = 3;
stmt = con.prepareStatement("INSERT INTO libros VALUES (?,?,?,?,?)");
stmt.setString(1,sISBN);
stmt.setInt(2,idAutor);
stmt.setString(3,sTitulo);
stmt.setString(4,sDescripcion);
stmt.setString(5,sCategoria);
int retorno = stmt.executeUpdate();
if (retorno>0)
System.out.println("Insertado correctamente");
} catch (SQLException sqle){
System.out.println("SQLState: "
+ sqle.getSQLState());
System.out.println("SQLErrorCode: "
+ sqle.getErrorCode());
sqle.printStackTrace();
} catch (Exception e){
e.printStackTrace();
} finally {
if (con != null) {
try{
stmt.close();
con.close();
} catch(Exception e){
e.printStackTrace();
}
}
}
}
}
Artículos
Vídeos Java
Disfruta también de nuestros artículos sobre Java en formato vídeo. Aprovecha y suscribete a nuestro canal.