网页与mysql数据库怎么连接?

网页与mysql数据库怎么连接?,第1张

连接方法如下:

1.建立一个web项目

2.把数据驱动复制到lib目录下。数据库驱动有:mysql,sqlserver,oracle等 是什么样类型的数据导入相应驱动。

3.编写一个连接数据库的工具类,获取一个连接。下面以mysql数据库为例。

核心代码:

public class DataUtils {

/**

* 从数据中获取一个连接

* @return

*/

public static Connection getConn(){

Connection conn = null

try {

Class.forName("com.mysql.jdbc.Driver").newInstance()

//表为test,用户名root,密码admin。

conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "admin")

} catch (Exception e) {

e.printStackTrace()

}

return conn

}

}

4.获取到与相应数据库的连接后,就可以做增删改查 *** 作了。记得做完 *** 作后,关闭连接,释放资源。

错误“Too many connections”。平常碰到这个问题,我基本上是修改/etc/my.cnf的max_connections参数,然后重启数据库。但是生产服务器上数据库又不能随便重启。没办法,只好想办法手动去释放一些没用的连接。登陆到MySQL的提示符下,数据show processlist这个命令,可以得到所以连接到这个服务器上的MySQL连接:mysql>show processlist+---------+------+---------------------+---------+---------+------+-------+-------------------+| Id | User | Host| db | Command | Time | State | Info |+---------+------+---------------------+---------+---------+------+-------+-------------------+| 1180421 | ur | 202.103.96.68:49754 | test1 | Sleep |1 | | NULL || 1180427 | ur | 202.103.96.68:55079 | test2 | Sleep |1 | | NULL || 1180429 | ur | 202.103.96.68:55187 | testdba | Sleep |0 | | NULL || 1180431 | ur | 202.103.96.68:55704 | testdba | Sleep |0 | | NULL || 1180437 | ur | 202.103.96.68:32825 | test1 | Sleep |1 | | NULL || 1180469 | ur | 202.103.96.68:58073 | testdba | Sleep |0 | | NULL || 1180472 | ur | 83.136.93.131:47613 | test2 | Sleep |8 | | NULL || 1180475 | root | localhost | NULL| Query |0 | NULL | show PROCESSLIST |+---------+------+---------------------+---------+---------+------+-------+-------------------+8 rows in set (0.00 sec)mysql>然后,你可以看到像上面这样的MySQL数据连接列表,而且每一个都会有一个进程ID号(在上表的第一列)。我们只要输入这样的命令:mysql>kill 1180421Query OK, 0 rows affected (0.00 sec)mysql>其中1180421为你在进程列表里找到并且要杀掉的进程号。产生这种问题的原因是:连接数超过了 MySQL 设置的值,与 max_connections 和 wait_timeout 都有关系。wait_timeout 的值越大,连接的空闲等待就越长,这样就会造成当前连接数越大。解决方法:修改MySQL配置文件/etc/my.cnf,设置成max_connections=1000,wait_timeout=5。如果没有此项设置可以自行添加,修改后重启MySQL服务即可。要不经常性报此错误,则要对服务器作整体性能优化注:为了防止发生too many connections时候无法登录的问题,mysql manual有如下的说明:mysqld actually allows max_connections+1 clients to connect. The extra connection is reserved for use by accounts that have the SUPER privilege. By granting the SUPER privilege to administrators and not to normal users (who should not need it), an administrator can connect to the server and use SHOW PROCESSLIST to diagnose problems even if the maximum number of unprivileged clients are connected.因此, 必须只赋予root用户的SUPER权限,同时所有数据库连接的帐户不能赋予SUPER权限。前面说到的报错后无法登录就是由于我们的应用程序直接配置的root用户 总结,解决问题的最终方法:1.修改配置文件/etc/my.cnf,调整连接参数2.检查程序代码,对于没有关闭的链接及时进行关闭


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/6229872.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-03-18
下一篇 2023-03-18

发表评论

登录后才能评论

评论列表(0条)

保存