Stack Holder Stack Holder - 5 months ago 29
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() {
initComponents();
}

@SuppressWarnings("unchecked")
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 {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
} catch (ClassNotFoundException ex) {
Logger.getLogger(apps.class.getName()).log(Level.SEVERE, null, ex);
}
Connection conn = DriverManager.getConnection(url, userName, password);

Answer

I simply added UserName and Password As:

import java.sql.*; 

public class Conection{

    public static void main(String a[]) throws ClassNotFoundException, SQLException
{
    try
    {
       /// String url = "jdbc:sqlserver://localhost\\MALIKUSMANNAWAZ:1433;databaseName=ali";
        Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
        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);
        while(rs.next())
        {
            System.out.println("Name: "+rs.getString(1));



            }
            if(st!=null)
            st.close();
            if(conn!=null)
                conn.close();
        }
        catch(SQLException sqle)
        {
            System.out.println("Sql exception "+sqle);
        }
    }
}