Stack Holder Stack Holder - 1 year ago 68
Java Question

Java and SQL Server 2012 Connection

I am using windows authentication in sql server 2012.

I want to connect java to sql.

I have following code (just for example AND Some code is missing as copied from netbeans you know)**

public app() {

private void UserNameActionPerformed(java.awt.event.ActionEvent evt) {

String username = UserName.getText();

private void PasswordActionPerformed(java.awt.event.ActionEvent evt) {
String password = Password.getText();

private void LoginActionPerformed(java.awt.event.ActionEvent evt) {

public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new app().setVisible(true);

// Variables declaration - do not modify
private javax.swing.JToggleButton Login;
private javax.swing.JPasswordField Password;
private javax.swing.JTextField UserName;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
// End of variables declaration

Database queries:

Create database ali;

use ali;

create table Login_System (
Username VARCHAR(50),
password VARCHAR(90)

SELECT * FROM Login_System;

String userName ="username";
String password ="password";

String url ="jdbc:sqlserver://localhost\\MALIKUSMANNAWAZ:1433;databaseName=ali";

try {
} catch (ClassNotFoundException ex) {
Logger.getLogger(apps.class.getName()).log(Level.SEVERE, null, ex);
Connection conn = DriverManager.getConnection(url, userName, password);

Answer Source

I simply added UserName and Password As:

import java.sql.*; 

public class Conection{

    public static void main(String a[]) throws ClassNotFoundException, SQLException
       /// String url = "jdbc:sqlserver://localhost\\MALIKUSMANNAWAZ:1433;databaseName=ali";
        Connection conn = DriverManager.getConnection("jdbc:sqlserver://localhost\\MALIKUSMANNAWAZ:1433;databaseName=ali","sa","dbase");
        System.out.println("connection created");
        Statement st=conn.createStatement();
        String sql="select * from Login_System";
        ResultSet rs=st.executeQuery(sql);
            System.out.println("Name: "+rs.getString(1));

        catch(SQLException sqle)
            System.out.println("Sql exception "+sqle);