Java examples for java.sql:SqlServer
Get PreparedStatement for sqlserver Database
//package com.java2s; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class Main { private static String driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver"; private static String url = "jdbc:jtds:sqlserver://192.168.81.16:55944;databaseName=ATDataBase"; private static String user = "uapp_autotest"; private static String password = "1qaz@wsx"; public static PreparedStatement getPreparedStatement(String cmdText, Object... cmdParams) { Connection conn = getConnection(); if (conn == null) { return null; }// ww w . ja va 2 s .c om PreparedStatement pstmt = null; try { pstmt = conn.prepareStatement(cmdText, ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); int i = 1; for (Object item : cmdParams) { pstmt.setObject(i, item); i++; } } catch (SQLException e) { e.printStackTrace(); close(conn); } return pstmt; } public static PreparedStatement getPreparedStatement(Connection conn, String cmdText, Object... cmdParams) { if (conn == null) { return null; } PreparedStatement pstmt = null; try { pstmt = conn.prepareStatement(cmdText, ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); int i = 1; for (Object item : cmdParams) { pstmt.setObject(i, item); i++; } } catch (SQLException e) { e.printStackTrace(); close(pstmt); } return pstmt; } public static Connection getConnection() { try { Class.forName(driver); } catch (ClassNotFoundException ex) { ex.printStackTrace(); } try { return DriverManager.getConnection(url, user, password); } catch (SQLException ex) { ex.printStackTrace(); return null; } } public static Connection getConnection(String connecturl, String username, String psw) { url = connecturl; user = username; password = psw; return getConnection(); } public static Connection getConnection(String connecturl) { url = connecturl; user = ""; password = ""; try { Class.forName(driver); } catch (ClassNotFoundException ex) { ex.printStackTrace(); } try { return DriverManager.getConnection(url); } catch (SQLException ex) { ex.printStackTrace(); return null; } } private static void close(Object obj) { if (obj == null) { return; } try { if (obj instanceof Statement) { ((Statement) obj).close(); } else if (obj instanceof PreparedStatement) { ((PreparedStatement) obj).close(); } else if (obj instanceof ResultSet) { ((ResultSet) obj).close(); } else if (obj instanceof Connection) { ((Connection) obj).close(); } } catch (SQLException ex) { ex.printStackTrace(); } } }