How to connect to your mssql database?
Connection connection = null; ResultSet resultSet = null; Statement statement = null; String dbConnector= "jdbc:odbc:"; // String dbname = "myDSNEntry"; //example - remember the System-DSN entry on your machine String name = "user="; //ad username after equals sign String pw = "password="; // add pw after equals sign try { // Load Driver Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); // get connected to ms sql server connection = DriverManager.getConnection(dbConnector + dbname + ";" + name + ";" + pw); // checking the database name statement = connection.createStatement(); resultSet = statement.executeQuery("SELECT DB_NAME()"); resultSet.next(); String dbname = resultSet.getString(1); System.out.println("Connected to database: "+dbname); // make query resultSet = statement .executeQuery("select * from tablename"); while (resultSet.next()) { // getString(1) ^= first Row System.out.println(resultSet.getString(1) + " | " + resultSet.getString(2)); } } catch (Exception e) { e.printStackTrace(); } finally { try { //close operations resultSet.close(); statement.close(); connection.close(); } catch (Exception e) { e.printStackTrace(); } }
Schreibe einen Kommentar