Created
December 21, 2014 22:04
-
-
Save elleryq/84b1478fff0c9a4b73e6 to your computer and use it in GitHub Desktop.
Java JDBC with jtds example. 1. Open SQL Configuration Manager to make sure that TCP/IP is enabled and IP/All port is 1433. 2. Open 'Service' to make sure SQL server browser is started. 3. Open SQL Management Studio to make sure user has the permission to access.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // If you cannot connect with SQL server(express), you can check here: http://stackoverflow.com/questions/10522120/connecting-to-local-ms-sql-server | |
| package com.example.jtdsexample; | |
| import java.sql.Connection; | |
| import java.sql.DriverManager; | |
| import java.sql.ResultSet; | |
| import java.sql.SQLException; | |
| public class Main { | |
| public static void main(String[] args) { | |
| new Main().start(); | |
| } | |
| private void start() { | |
| System.out.println("START"); | |
| String query = "SELECT * FROM Fruits"; | |
| ResultSet rs = getData(query); | |
| try { | |
| while (rs.next()) { | |
| System.out.println(rs.getString("name")); | |
| } | |
| } catch (SQLException e) { | |
| e.printStackTrace(); | |
| } | |
| System.out.println("END"); | |
| } | |
| public ResultSet getData(String query) { | |
| Connection CON = null; | |
| try { | |
| Class.forName("net.sourceforge.jtds.jdbc.Driver"); | |
| CON = DriverManager.getConnection(URL, USER, PASS); | |
| RESULT = CON.createStatement().executeQuery(query); | |
| } catch (Exception ex) { | |
| ex.printStackTrace(); | |
| } | |
| return RESULT; | |
| } | |
| private String URL = "jdbc:jtds:sqlserver://localhost:1433/Sample;instance=SQLEXPRESS;"; | |
| private String USER = "sampleuser"; | |
| private String PASS = "sampleuser"; | |
| private static ResultSet RESULT; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment