angel
angel

Reputation: 4642

Why I don't get a connection? Java.. SQL Server Express Edition (server)

Where do I have a bug? A mistake? Why can't I connect? My code,

    package conexiones;
    import java.sql.DriverManager;
    import java.sql.Connection;

    public class miconexion {
        static String db = "futbol";
        static String url = "jdbc:sqlserver://localhost;databaseName="+db+";";

        //(local)\SQLEXPRESS
        //String conn;
        public Connection conn;

        public miconexion() {
            try
            {
                Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
                conn=DriverManager.getConnection(url);
                System.out.println("conexion exitosa");
            }
            catch(Exception e)
            {
                System.out.println(e);
                System.out.println("no conectado");
            }
        }

        public Connection getConnection()
        {
            return conn;
        }

        public void desconectar()
        {
            conn=null;
        }

        public static void main(String [] ar )
        {
            miconexion con = new miconexion();
            con.getConnection();
        }
    }

Upvotes: 0

Views: 3210

Answers (5)

engtuncay
engtuncay

Reputation: 887

My code can help you, you can connect over 127.0.0.1 on your machine.

sqlserver express connection over servername\instancename

also you should enable tcp/ip in sql configuration, and also enable for ip ( 127.0.0.1)

Upvotes: 0

Bala R
Bala R

Reputation: 109037

Since you are using SQL Server Express Edition, try

static String url="jdbc:sqlserver://localhost\\SQLEXPRESS;databaseName="+db+";";

Upvotes: 1

Manish Singh
Manish Singh

Reputation: 3499

If you have liberty to choose on Db driver. Go for JTDS opensource driver for SQL Server.

Connection String example..

jdbc:jtds:<server_type>://<server>[:<port>][/<database>][;<property>=<value>[;...]]

Upvotes: 0

Jeremy
Jeremy

Reputation: 607

You may need to enable basic authentication. By default MS SQL Server only accepts trusted (aka Windows login) connections. You'll also need to create a user and specify the username and password in the connection string.

Upvotes: 0

Chris Nava
Chris Nava

Reputation: 6802

By default MS SQL Server (and probably Express) is not enabled for TCP (JDBC) connections. You need to go into the server configuration and enable TCP.

Upvotes: 1

Related Questions