java如何连接到mysql,如何连接MySQL到Java程序

I ve installed MySQL (last update).

I need to code, that ll create & establish a connection with SQL DB

& manage the DB(using SELECT, INSERT, CREATE).

I did everything but, I am not able to create connection. I've also installed the MySQL/J connector, I just extracted the .zip pack in a folder & added the folder path in Variables).

Can anyone tell me wat is meant by URL in the below line?

Connection connection = DriverManager.getConnection(url, username, password);

I ve tried this:

String url = "jdbc:odbc:sqlserver://localhost:3306/myfirstdb";

Connection con = DriverManager.getConnection(url, "root", "1234");

But it's not working. I am unable able to understand the term 'URL'.

Can anyone explain, the meaning of 'url' and wat should be done to connect to a SQL server from Java.

Update:

This is the Full code. It still cannot connect.

import java.sql.*;

public class TestDriver {

public static void main(String[] args) {

try {

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");//This s wat actually i did for connection

System.out.println("Driver Loaded Succesfully");

}

catch (Exception e){

System.out.println("Unable to Load Driver!!!");

}

try {

Class.forName(com.mysql.jdbc.Driver"); // initialise the driver

String url ="jdbc:mysql://localhost:3306/myfirstdb";

Connection con = DriverManager.getConnection(url, "root", "1234");

System.out.println("connection Established");

}

catch(Exception e) {

System.out.println("Couldnt get connection");

}

}

}

Can you tell me wat is the purpose of MySQL Connector/J?

解决方案

In the question you seem to be using a MySQL jdbc driver with a SQL Server jdbc URL. This won't work.

If you are using a MySQL database:

Class.forName("com.mysql.jdbc.Driver"); // initialise the driver

String url ="jdbc:mysql://localhost:3306/myfirstdb";

If you are using a SQL Server database you are going to need a completely different jdbc driver. jTDS is open source and a good option. Include the jtds.jar file in your classpath and use something like:

Class.forName("net.sourceforge.jtds.jdbc.Driver"); // initialise the driver

String url = "jdbc:jtds:sqlserver://localhost:1433/myfirstdb";

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值