@Override public Set<EmpVO> getEmpsByDeptno(Integer deptno) { Set<EmpVO> set = new LinkedHashSet<EmpVO>(); EmpVO empVO = null; Connection con = null; PreparedStatement pstmt = null; ResultSet rs = null; try { Class.forName(driver); con = DriverManager.getConnection(url, userid, passwd); pstmt = con.prepareStatement(GET_Emps_ByDeptno_STMT); pstmt.setInt(1, deptno); rs = pstmt.executeQuery(); while (rs.next()) { empVO = new EmpVO(); empVO.setEmpno(rs.getInt("empno")); empVO.setEname(rs.getString("ename")); empVO.setJob(rs.getString("job")); empVO.setHiredate(rs.getDate("hiredate")); empVO.setSal(rs.getDouble("sal")); empVO.setComm(rs.getDouble("comm")); empVO.setDeptno(rs.getInt("deptno")); set.add(empVO); // Store the row in the vector } // Handle any driver errors } catch (ClassNotFoundException e) { throw new RuntimeException("Couldn't load database driver. " + e.getMessage()); // Handle any SQL errors } catch (SQLException se) { throw new RuntimeException("A database error occured. " + se.getMessage()); } finally { if (rs != null) { try { rs.close(); } catch (SQLException se) { se.printStackTrace(System.err); } } if (pstmt != null) { try { pstmt.close(); } catch (SQLException se) { se.printStackTrace(System.err); } } if (con != null) { try { con.close(); } catch (Exception e) { e.printStackTrace(System.err); } } } return set; }
public ArrayList<Funcionario> consultarTodosFuncionarios() { ArrayList<Funcionario> arrayList = new ArrayList<Funcionario>(); BancoDados banco = new BancoDados(); try { Class.forName(banco.getDriver()); Connection conn = DriverManager.getConnection(banco.getStr_conn(), banco.getUsuario(), banco.getSenha()); Statement stmt = conn.createStatement(); String sql = "select * from Funcionario order by funcionarioNome asc"; ResultSet rs = stmt.executeQuery(sql); while (rs.next()) { Funcionario funcionario = new Funcionario(); funcionario.setFuncionarioId(rs.getInt("funcionarioId")); funcionario.setFuncionarioNome( rs.getString("funcionarioNome") + " - " + rs.getString("funcionarioCpf")); arrayList.add(funcionario); } } catch (ClassNotFoundException ex) { System.out.println("Não foi possivel carregar o driver."); ex.printStackTrace(); } catch (SQLException ex) { System.out.println("Problema com SQL."); ex.printStackTrace(); } return arrayList; }
// Yhteyden avaaminen public boolean avaaYhteys() { // Vaihe 1: tietokanta-ajurin lataaminen try { Class.forName(AJURI); } catch (ClassNotFoundException e) { System.out.println("Ajurin lataaminen ei onnistunut. Lopetetaan ohjelman suoritus."); e.printStackTrace(); return false; } // Vaihe 2: yhteyden ottaminen tietokantaan con = null; try { con = DriverManager.getConnection( PROTOKOLLA + "//" + PALVELIN + ":" + PORTTI + "/" + TIETOKANTA, KAYTTAJA, SALASANA); stmt = con.createStatement(); // Toiminta mahdollisessa virhetilanteessa } catch (SQLException e) { System.out.println("Yhteyden avaamisessa tapahtui seuraava virhe: " + e.getMessage()); e.printStackTrace(); return false; } return true; }
public void conectarBDdinamic(String ip) { if (ip == null) { ip = "192.168.8.231"; } url = "jdbc:postgresql://" + ip + "/ventasalm"; // javax.swing.JOptionPane.showMessageDialog(null, url); String estado; try { final String CONTROLADOR = "com.microsoft.sqlserver.jdbc.SQLServerDriver"; Class.forName(CONTROLADOR); // System.getProperty( "user.dir" )+"/CarpetaBD/NombredelaBasedeDatos.mdb"; conexion = DriverManager.getConnection(url, user, pass); sentencia = conexion.createStatement(); // estado="Conectado Correctamente"; } catch (ClassNotFoundException ex1) { ex1.printStackTrace(); javax.swing.JOptionPane.showMessageDialog(null, "Error Carga Driver"); estado = "Servidor no esta disponible"; // System.exit(1); } catch (SQLException ex) { ex.printStackTrace(); javax.swing.JOptionPane.showMessageDialog(null, "Error Creacion Statement"); estado = "Servidor no esta disponible"; // System.exit(1); } // return estado; }
public DBConn(Properties p) { try { Class.forName("oracle.jdbc.driver.OracleDriver"); } catch (ClassNotFoundException e) { System.out.println("No Oracle JDBC Driver found."); e.printStackTrace(); return; } try { connection = DriverManager.getConnection( p.getProperty("db_adr"), p.getProperty("db_usr"), p.getProperty("db_pwd")); } catch (SQLException e) { e.printStackTrace(); } if (connection == null) { System.out.println("Failed to make connection!"); } else { try { connection.setAutoCommit(false); System.out.println("Connection established and ready to work."); } catch (SQLException e) { System.out.println("Can't turn off autocommit mode."); e.printStackTrace(); } } }
// get drivername, user, pw & server, and return connection id public void serve(InputStream i, OutputStream o) throws IOException { // TODOServiceList.getSingleInstance(); initialize(); NameListMessage nameListMessage = null; try { // read input to know which target panel is required ObjectInputStream input = new ObjectInputStream(i); nameListMessage = (NameListMessage) input.readObject(); // parse the required panel parseSqlFile(nameListMessage); } catch (ClassNotFoundException ex) { if (Debug.isDebug()) ex.printStackTrace(); nameListMessage.errorMessage = ex.toString(); } // send object to the caller ObjectOutputStream output = new ObjectOutputStream(o); output.writeObject(nameListMessage); // end socket connection o.close(); i.close(); }
public static void main(String[] args) { try { Class.forName("com.mysql.jdbc.Driver"); // Connection conexion = // DriverManager.getConnection("jdbc:mysql://192.168.0.60:3306/juancarlos", "santi", "santi"); Connection conexion = DriverManager.getConnection("jdbc:mysql://192.168.0.60:3306/mydb", "santi", "santi"); Statement consulta = conexion.createStatement(); ResultSet resultado; resultado = consulta.executeQuery("select * from persona"); while (resultado.next()) { String nombre = resultado.getString("nombre"); String apellidos = resultado.getString("direccion"); int edad = resultado.getInt("edad"); System.out.println(nombre + " - " + apellidos + " - Edad: " + edad); } } catch (ClassNotFoundException e) { System.out.println("No he encontrado la clase error: " + e.getMessage()); } catch (SQLException e) { System.out.println("No se puede conectar a la base de datos error: " + e.getMessage()); } }
public String insertarEmpleado(Empleado empleado) { String mensaje = null; try { cn = Conexion.realizarConexion(); String sql = "insert into empleado values(?,?,?,?,?,?,?,?)"; ps = cn.prepareStatement(sql); ps.setString(1, empleado.getCodigo()); ps.setString(2, empleado.getPaterno()); ps.setString(3, empleado.getMaterno()); ps.setString(4, empleado.getNombre()); ps.setString(5, empleado.getCiudad()); ps.setString(6, empleado.getDireccion()); ps.setString(7, empleado.getUsuario()); ps.setString(8, empleado.getClave()); ps.executeUpdate(); } catch (ClassNotFoundException ex) { mensaje = ex.getMessage(); } catch (SQLException ex) { mensaje = ex.getMessage(); } finally { try { ps.close(); cn.close(); } catch (Exception ex) { mensaje = ex.getMessage(); } } return mensaje; }
public String buscarEmpleado(String codigo) { try { cn = Conexion.realizarConexion(); st = cn.createStatement(); String sql = "select chr_emplcodigo from empleado " + " where chr_emplcodigo = '" + codigo + "'"; rs = st.executeQuery(sql); while (rs.next()) { return rs.getString("chr_emplcodigo"); } } catch (ClassNotFoundException ex) { showMessageDialog(null, ex.getMessage(), "Excepción", 0); } catch (SQLException ex) { showMessageDialog(null, ex.getMessage(), "Excepción", 0); } finally { try { rs.close(); st.close(); cn.close(); } catch (Exception ex) { showMessageDialog(null, ex.getMessage(), "Excepción", 0); } } return null; }
protected boolean insertComment() throws SQLException { try { String dburl = getServletContext().getInitParameter("DBUrl"); String dbuser = getServletContext().getInitParameter("DBUser"); String dbpasswd = getServletContext().getInitParameter("DBPasswd"); Class.forName("com.mysql.jdbc.Driver"); conn = DriverManager.getConnection(dburl, dbuser, dbpasswd); String sqlqry = "INSERT INTO feedback (name, email, feedback) VALUES (?,?,?)"; pstmt = conn.prepareStatement(sqlqry); pstmt.setString(1, name); pstmt.setString(2, email); pstmt.setString(3, comment); if (pstmt.executeUpdate() > 0) return true; } catch (ClassNotFoundException e) { // TODO Auto-generated catch block logger.error(e); e.printStackTrace(); } catch (SQLException e) { // TODO Auto-generated catch block logger.error(e); e.printStackTrace(); } finally { conn.close(); pstmt.close(); } return false; }
public TestaSelect(int num_) { Connection connection = null; Statement statement = null; int numero = num_; try { Class.forName(JDBC_DRIVER); connection = DriverManager.getConnection("jdbc:mysql://localhost/test", "root", ""); System.out.println("Conectado: " + connection); statement = connection.createStatement(); ResultSet resultSet = statement.executeQuery("select * from fatura where numero=" + numero); while (resultSet.next()) { System.out.println("Numero: " + resultSet.getInt("numero")); System.out.println("Nome: " + resultSet.getString("nome")); System.out.println("Valor: " + resultSet.getInt("valor")); System.out.println(); } } catch (ClassNotFoundException classNotFound) { System.out.println("Driver nao foi encontrado"); classNotFound.printStackTrace(); } catch (SQLException sqlException) { System.out.println("Erro na conexao"); sqlException.printStackTrace(); } finally { try { connection.close(); statement.close(); } catch (Exception e) { System.out.println("Erro durante fechamento da conexao"); e.printStackTrace(); System.exit(1); } } }
public static String getCurrentProfile() { String url = "jdbc:mysql://" + var.db_host + "/" + var.db_name; String login = var.db_username; String passwd = var.db_psswd; Connection cn = null; Statement stmt = null; String query = "SELECT Name FROM profile WHERE ID='0';"; try { Class.forName("com.mysql.jdbc.Driver"); cn = DriverManager.getConnection(url, login, passwd); stmt = cn.createStatement(); ResultSet rs = stmt.executeQuery(query); while (rs.next()) { return rs.getString("Name"); } } catch (SQLException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } finally { if (stmt != null) { try { stmt.close(); } catch (SQLException e) { e.printStackTrace(); } } } return ""; }
/** * Obtenir une nouvelle connexion a la BD, en fonction des parametres contenus dans un fichier de * configuration. * * @return une nouvelle connexion a la BD * @throws ExceptionConnexion si la connexion a echoue */ public static Connection getConnexion(String login, String mdp) throws ExceptionConnexion { Connection conn = null; try { // lecture des parametres de connexion dans connection.conf Properties p = new Properties(); InputStream is = null; is = new FileInputStream(utils.Constantes.Home + utils.Constantes.Config); p.load(is); String url = p.getProperty("url"); String driver = p.getProperty("driver"); Class.forName(driver); // hopper@UFR, Oracle conn = DriverManager.getConnection(url, login, mdp); conn.setAutoCommit(false); } catch (SQLException e) { System.out.println("Connexion impossible : " + e.getMessage()); // handle any errors System.out.println("SQLException: " + e.getMessage()); System.out.println("SQLState: " + e.getSQLState()); System.out.println("VendorError: " + e.getErrorCode()); } catch (IOException e) { throw new ExceptionConnexion("fichier conf illisible \n" + e.getMessage()); } catch (ClassNotFoundException e) { throw new ExceptionConnexion("problème d'identification du pilote \n" + e.getMessage()); } return conn; }
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter writer = response.getWriter(); String noteName = request.getParameter("noteName"); String note = request.getParameter("note"); try { Class.forName("com.mysql.jdbc.Driver"); Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/evernoteDB"); Statement st = con.createStatement(); st.executeUpdate( "INSERT INTO note (noteName, note) VALUES ('" + noteName + "','" + note + "')"); response.sendRedirect("/userNotes.jsp"); } catch (ClassNotFoundException e) { writer.println("Couldn't load database driver: " + e.getMessage()); } catch (SQLException e) { writer.println("SQLException caught: " + e.getMessage()); } catch (Exception e) { writer.println(e); } }
public static int admininsertform(HttpServletRequest request) { int rtn = 0; String pid = request.getParameter("pid"); String pname = request.getParameter("pname"); String pprice = request.getParameter("pprice"); String pmount = request.getParameter("pmount"); String pseller = request.getParameter("pseller"); String mailcost = request.getParameter("mailcost"); if (pid == null || pid.equals("")) { } else { try { Class.forName("com.mysql.jdbc.Driver"); Connection conn = DriverManager.getConnection( "jdbc:mysql://localhost:3306/shop?user=root&password=root&useUnicode=true&characterEncoding=GB2312"); String sql = "insert into production values(?,?,?,?,?,?)"; PreparedStatement psmt = conn.prepareStatement(sql); psmt.setString(1, pid); psmt.setString(2, pname); psmt.setString(3, pprice); psmt.setString(4, pmount); psmt.setString(5, pseller); psmt.setString(6, mailcost); rtn = psmt.executeUpdate(); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } } return rtn; }
public ArrayList<Empleado> listarEmpleado() { ArrayList<Empleado> emple = new ArrayList<Empleado>(); try { cn = Conexion.realizarConexion(); st = cn.createStatement(); String sql = "select * from empleado"; rs = st.executeQuery(sql); while (rs.next()) { emple.add( new Empleado( rs.getString(1), rs.getString(2), rs.getString(3), rs.getString(4), rs.getString(5), rs.getString(6), rs.getString(7), rs.getString(8))); } } catch (ClassNotFoundException ex) { showMessageDialog(null, ex.getMessage(), "Excepción", 0); } catch (SQLException ex) { showMessageDialog(null, ex.getMessage(), "Excepción", 0); } finally { try { rs.close(); st.close(); cn.close(); } catch (Exception ex) { showMessageDialog(null, ex.getMessage(), "Excepción", 0); } } return emple; }
public DBStorage(String url, String dbName, String username, String password) throws SQLException { this.username = username; this.password = password; this.DBName = dbName; this.DB_URL = url; this.DBName = dbName; try { Class.forName("org.gjt.mm.mysql.Driver"); } catch (ClassNotFoundException e) { e.printStackTrace(); } Connection tmpConnection = DriverManager.getConnection(DB_URL, username, password); Statement stmt = tmpConnection.createStatement(); stmt.executeUpdate("CREATE DATABASE IF NOT EXISTS " + dbName); stmt.close(); tmpConnection.close(); this.connection = DriverManager.getConnection(DB_URL + dbName, username, password); System.out.println("Database created successfully..."); }
/** Creates new form mSubcon */ public mSubcon() { initComponents(); tblSubcon.setModel(tblModel); Table(tblSubcon, new int[] {120, 150, 120, 120}); try { Class.forName("com.mysql.jdbc.Driver"); // MENYIAPKAN KONEKSI DAN PARAMETERNYA String urldb = "jdbc:mysql://localhost:3306/expedisi"; String user = "******"; String password = ""; Connection koneksi = DriverManager.getConnection(urldb, user, password); // Query SQL dan Eksekuusinya String strSQL = "SELECT id_kota,namakota from t_kota"; Statement st = koneksi.createStatement(); ResultSet rs = st.executeQuery(strSQL); while (rs.next()) { cmbKota.addItem(new masukan(rs.getInt(1), rs.getString(2).trim()).getLabel()); } rs.close(); st.close(); koneksi.close(); } catch (ClassNotFoundException cnfe) { System.out.println("KESALAHAN SAAT" + "ME-LOAD DRIVER JDBC \n" + cnfe.getMessage()); } catch (SQLException sqle) { System.out.println( "KESALAHAN SAAT KONEKSI ATAU " + "KESALAHAN QUERY SQL \n" + sqle.getMessage()); } setDefaultTable(); }
/* Constructeur : ouvre la connexion */ private ConnexionMySQL() { try { Class.forName("com.mysql.jdbc.Driver"); } catch (ClassNotFoundException classe) { System.out.println(classe.toString()); } connected = false; url = "jdbc:mysql://localhost/tfe_memoir"; // en local // String url = "jdbc:mysql://sql.info.iepscf-uccle.be/sonneville"; //à l'école try { /* setup the properties: si les accents ne sont pas Unicode ds la BDD java.util.Properties prop = new java.util.Properties(); prop.put("charSet", "ISO-8859-15"); prop.put("user", username); prop.put("password", password);*/ // Connect to the database conn = DriverManager.getConnection(url, "root", ""); // en local // conn=DriverManager.getConnection(url, "sonneville",""); // à l'école stat = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE); // on peut parcourir le résultat dans les 2 sens, insensible aux chgmts d'autrui // on peut modifier ce résultat pour ensuite reporter ces modifs ds la table (updateRow) conn.setAutoCommit(false); connected = true; } catch (SQLException e) { System.out.println(e.toString()); } }
private void btHapusActionPerformed( java.awt.event.ActionEvent evt) { // GEN-FIRST:event_btHapusActionPerformed try { Class.forName("com.mysql.jdbc.Driver"); // MENYIAPKAN KONEKSI DAN PARAMETERNYA String urldb = "jdbc:mysql://localhost:3306/expedisi"; String user = "******"; String password = ""; Connection koneksi = DriverManager.getConnection(urldb, user, password); // Query SQL dan Eksekuusinya Statement st = koneksi.createStatement(); String strSQL = "delete from t_subcon where namasubcon='" + txtNamSub.getText() + "'"; st.executeUpdate(strSQL); tblModel.removeRow(row); txtNamSub.setText(""); txtAlamat.setText(""); txtTelp.setText(""); st.close(); koneksi.close(); } catch (ClassNotFoundException cnfe) { System.out.println("KESALAHAN SAAT" + "ME-LOAD DRIVER JDBC \n" + cnfe.getMessage()); } catch (SQLException sqle) { System.out.println( "KESALAHAN SAAT KONEKSI ATAU " + "KESALAHAN QUERY SQL \n" + sqle.getMessage()); } // TODO add your handling code here: } // GEN-LAST:event_btHapusActionPerformed
// AQUI VOYA OBTENER EL SERVDUIOR QUEMADO EN UN ARCHIVO DE TEXTO public void conectarBaseDeDatos2() { try { final String CONTROLADOR = "org.postgresql.Driver"; Class.forName(CONTROLADOR); // System.getProperty( "user.dir" )+"/CarpetaBD/NombredelaBasedeDatos.mdb"; conexion = DriverManager.getConnection(url2, user, pass); sentencia = conexion.createStatement(); /*JOptionPane.showMessageDialog(null, "si conecta");*/ } catch (ClassNotFoundException ex1) { // ex1.printStackTrace(); javax.swing.JOptionPane.showMessageDialog(null, "Error Carga Driver." + ex1.getMessage()); System.exit(1); } catch (SQLException ex) { // ex.printStackTrace(); javax.swing.JOptionPane.showMessageDialog( null, "Error Creacion Statement." + ex.getMessage() + " / " + url2 + " / " + user + " / " + pass); System.exit(1); } }
public void setDefaultTable() { String stat = ""; try { Class.forName("com.mysql.jdbc.Driver"); // MENYIAPKAN KONEKSI DAN PARAMETERNYA String urldb = "jdbc:mysql://localhost:3306/expedisi"; String user = "******"; String password = ""; Connection koneksi = DriverManager.getConnection(urldb, user, password); // Query SQL dan Eksekuusinya String strSQL = "select namasubcon,alamat,kota,telp from t_subcon"; Statement st = koneksi.createStatement(); ResultSet rs = st.executeQuery(strSQL); while (rs.next()) { data[0] = rs.getString(1); data[1] = rs.getString(2); data[2] = rs.getString(3); data[3] = rs.getString(4); tblModel.addRow(data); } rs.close(); st.close(); koneksi.close(); } catch (ClassNotFoundException cnfe) { System.out.println("KESALAHAN SAAT" + "ME-LOAD DRIVER JDBC \n" + cnfe.getMessage()); } catch (SQLException sqle) { System.out.println( "KESALAHAN SAAT KONEKSI ATAU " + "KESALAHAN QUERY SQL \n" + sqle.getMessage()); } }
public void conectarBaseDeDatos() { try { final String CONTROLADOR = "org.postgresql.Driver"; Class.forName(CONTROLADOR); // System.getProperty( "user.dir" )+"/CarpetaBD/NombredelaBasedeDatos.mdb"; conexion = DriverManager.getConnection( "jdbc:postgresql://" + main.ipSeleccionada + "/" + objUtils.nameBD, user, pass); // conexion = DriverManager.getConnection("jdbc:postgresql://127.0.0.1/goliak_jg", "postgres", // "majcp071102kaiser"); sentencia = conexion.createStatement(); /*JOptionPane.showMessageDialog(null, "si conecta");*/ } catch (ClassNotFoundException ex1) { // ex1.printStackTrace(); javax.swing.JOptionPane.showMessageDialog(null, "Error Carga Driver." + ex1.getMessage()); System.exit(1); } catch (SQLException ex) { // ex.printStackTrace(); javax.swing.JOptionPane.showMessageDialog( null, "Error Creacion Statement." + ex.getMessage() + " / " + url + " / " + user + " / " + pass); System.exit(1); } }
DatabaseHelper() { try { Class.forName("com.mysql.jdbc.Driver"); } catch (ClassNotFoundException e) { e.printStackTrace(); } }
@Override public void delete(Integer deptno) { int updateCount_EMPs = 0; Connection con = null; PreparedStatement pstmt = null; try { Class.forName(driver); con = DriverManager.getConnection(url, userid, passwd); // 1●設定於 pstm.executeUpdate()之前 con.setAutoCommit(false); // 先刪除員工 pstmt = con.prepareStatement(DELETE_EMPs); pstmt.setInt(1, deptno); updateCount_EMPs = pstmt.executeUpdate(); // 再刪除部門 pstmt = con.prepareStatement(DELETE_DEPT); pstmt.setInt(1, deptno); pstmt.executeUpdate(); // 2●設定於 pstm.executeUpdate()之後 con.commit(); con.setAutoCommit(true); System.out.println("刪除部門編號" + deptno + "時,共有員工" + updateCount_EMPs + "人同時被刪除"); // Handle any driver errors } catch (ClassNotFoundException e) { throw new RuntimeException("Couldn't load database driver. " + e.getMessage()); // Handle any SQL errors } catch (SQLException se) { if (con != null) { try { // 3●設定於當有exception發生時之catch區塊內 con.rollback(); } catch (SQLException excep) { throw new RuntimeException("rollback error occured. " + excep.getMessage()); } } throw new RuntimeException("A database error occured. " + se.getMessage()); } finally { if (pstmt != null) { try { pstmt.close(); } catch (SQLException se) { se.printStackTrace(System.err); } } if (con != null) { try { con.close(); } catch (Exception e) { e.printStackTrace(System.err); } } } }
public void actionPerformed(java.awt.event.ActionEvent evt) { String sql1 = "select a.* FROM ANTENA a WHERE a.ID_antena='" + (newJPanel.jList1.getSelectedIndex() + 1) + "' "; String pom = ""; System.out.println(sql1); try { Class.forName("oracle.jdbc.driver.OracleDriver"); Connection conn; try { conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl", user, password); Statement stmt1 = conn.createStatement(); ResultSet rs1 = stmt1.executeQuery(sql1); while (rs1.next()) { NewJPanel.jTextField1.setText(rs1.getString("ID_antena")); NewJPanel.jTextField2.setText(rs1.getString("Producent")); NewJPanel.jTextField3.setText(rs1.getString("Numer_identyfikacyjny")); NewJPanel.jTextField4.setText(rs1.getString("Czestotliwosc")); NewJPanel.jTextField5.setText(rs1.getString("Polaryzacja")); NewJPanel.jTextField6.setText(rs1.getString("Moc")); NewJPanel.jTextField7.setText(rs1.getString("Rodzaj")); } } catch (SQLException e1) { System.out.println("tutaj 1"); e1.printStackTrace(); } } catch (ClassNotFoundException e1) { System.out.println("tutaj 2"); e1.printStackTrace(); } }
@Override public boolean connect() { try { Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver").newInstance(); String url = "jdbc:sqlserver://" + Config.DATABASE_IP + ":" + Config.DATABASE_PORT + ";databaseName=Narda"; conn = DriverManager.getConnection(url, Config.DATABASE_USERNAME, Config.DATABASE_PASSWORD); OrbitStamps.log(OrbitStamps.LOG_NOTICE, "HuddingeDataMapper: connection success!"); return true; } catch (ClassNotFoundException ex) { System.err.println(ex.getMessage()); } catch (IllegalAccessException ex) { System.err.println(ex.getMessage()); } catch (InstantiationException ex) { System.err.println(ex.getMessage()); } catch (SQLException ex) { System.err.println(ex.getMessage()); } OrbitStamps.log(OrbitStamps.LOG_NOTICE, "HuddingeDataMapper: connection failed!"); return false; }
public static void main(String[] args) throws SQLException, ClassNotFoundException, JSONException { PostgresDb db = new PostgresDb(); // db.setUrl("jdbc:postgresql://localhost:5432/powaaim"); try { Class.forName("org.postgresql.Driver"); c = DriverManager.getConnection(db.getUrl(), db.getUser(), db.getPass()); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } st = c.createStatement(); rs = st.executeQuery("SELECT id, name, externalshopid from shop where name='David_3'"); System.out.println("id" + " " + "name" + " " + "externalshopid"); c.close(); obj = new JSONObject(); while (rs.next()) { int id = rs.getInt("id"); String externaId = rs.getString("externalshopid"); String name = rs.getString("name"); // System.out.println(id+ " " + " "+ name + " " +" "+ externaId); System.out.println(); obj.put("id", id); obj.put("name", name); obj.put("externalshopid", externaId); System.out.print(obj); } }
{ try { Class.forName(JDBC_DRIVER); } catch (ClassNotFoundException e) { e.printStackTrace(); } }
public Funcionario consultarFuncionario(Funcionario funcionario) { Funcionario dadosFuncionario = new Funcionario(); BancoDados banco = new BancoDados(); try { Class.forName(banco.getDriver()); Connection conn = DriverManager.getConnection(banco.getStr_conn(), banco.getUsuario(), banco.getSenha()); Statement stmt = conn.createStatement(); String sql = "select * from Funcionario where funcionarioId = " + funcionario.getFuncionarioId(); ResultSet rs = stmt.executeQuery(sql); rs.next(); dadosFuncionario.setFuncionarioCpf(rs.getString("funcionarioCpf")); dadosFuncionario.setFuncionarioSenha(rs.getString("funcionarioSenha")); dadosFuncionario.setFuncionarioEmail(rs.getString("funcionarioEmail")); dadosFuncionario.setFuncionarioNome(rs.getString("funcionarioNome")); dadosFuncionario.setFuncionarioAcesso(rs.getInt("funcionarioAcesso")); } catch (ClassNotFoundException ex) { System.out.println("Não foi possivel carregar o driver."); ex.printStackTrace(); } catch (SQLException ex) { System.out.println("Problema com SQL."); ex.printStackTrace(); } return dadosFuncionario; }