How to get started with PostgreSQL similar to MySQL - mysql

I am not getting a clue to:
simply login to postgreSQL
Create a database
Add a table
Insert a record
Delete , update etc
These things are normally very very easy using mysql . Can someone help me setup following alternative for postgresql
a) Reset default password -- Very Clean description ,
I do not find same level of clarity for PostgreSQL
(Any documentation link is highly appreciated)
b) We know the superuser for mysql is "root" what is the same for PostgreSQL
c) from command line how to ( PostgreSQL ones ?):
mysql -uroot -proot
create database testdb;
use testdb;
create table test(id int(11) auto_increment, name varchar(20), primary key(id));
insert into test(name) values("testing one"),("testing two"),("testing three"),("testing four");
select * from test;
update test set name=concat(name,now()) where id =3;
delete from test where id =4;
drop table if exists test;
drop database if exists testdb;
EDIT MAC OS
# Default password reset
sudo mate /Library/PostgreSQL/9.2/data/pg_hba.conf
replaced (md5 with trust)
# "local" is for Unix domain socket connections only
local all all md5
# IPv4 local connections:
host all all 127.0.0.1/32 md5
# IPv6 local connections:
host all all ::1/128 md5
with
# "local" is for Unix domain socket connections only
local all all trust
# IPv4 local connections:
host all all 127.0.0.1/32 trust
# IPv6 local connections:
host all all ::1/128 trust
save
executed the Reload Configuration.app
login to postgresql without password :
$ psql -U postgres
postgres# ALTER USER postgres WITH PASSWORD 'new password';
\q
-revert back all the changes in pg_hba.conf (replace trust with md5) and save
-reload configuration
Now I can login to postgresql with new password
psql -U postgres
Password for user postgres:[my new password]

To login:
psql -d postgres_dbname -U postgres
Create Database:
create database testuser;
\c testuser; /*use testuse as mysql*/
Create Table:
create table employee (Name char(20));
Insert :
insert into employee VALUES ('XAS');
Update Link
Delete Link
Reset Password : See Here &
See Here Too

Simply login to postgreSQL
psql -U postgres -W template1
-U = username
postgres is root
-W = ask for password
tempalte1 = default database
Create a database
-- Create the database from within postgresql
create database my_database_name
-- Connect to the database
\c my_database_name
-- Create the database without logging in
createdb -U postgres -W my_database_name
Add a table
Insert a record
Delete , update etc
All the above from 3 to 5 are like in MySQL
For resetting postgres forgotten password this link is a good reference.

postgresql is a completely different system than mysql; so do not assume things will be like mysql. They are completely different animals entirely; some of your SQL statements might not work, especially if you are using a MySQL proprietary command.
To login to postgresql, use the psql command shell
CREATE DATABASE
CREATE TABLE
INSERT
For all other basic SQL commands, consider going through the tutorial
User access control is something more fine grained and detailed in postgresql. There are users and roles. A user is simply a role that has the ability to login (like MySQL), but in postgresql you can have roles (an account) that cannot login.
What access a role has is defined in pg_hba.conf. This file defines if a role can login at all, by what means are they authenticated, from where they can login and what database they have access to.
ALTER USER is used to reset credentials.
The "root user" for postgresql is typically postgres; and this is a system user that is created during the install process. For Windows, the binary installer will ask if you want to launch the service as this user as well.

Please take a look at this PostgreSQL error 'Could not connect to server: No such file or directory'
Try to install postgresApp, this solved my problem which was the same of yours.

Related

How to re-setup Database configurations in Icinga2 server?

I am using ubuntu 16.04 and mysql DB ,i configured DB for icinga2 server and i created separate user in database.
somedays back i deleted that user from db now i am not able access icingaweb2 UI,
Getting below error while trying to access to the link.
All configured authentication methods failed. Please check the system log or Icinga Web 2 log for more information.
I followed the below link to install icinga2 server
Please Help.
I resolved the issue by re-creatinging a setup token in in the Icinga Web 2 by using bellow command
sudo icingacli setup token create
i got some error's while creating setup token and it is easily resolved by using [1]: https://monitoring-portal.org/index.php?thread/40111-icingacli-does-not-work/
If you still have access to the MySQL DB you should do a backup first of your icinga2 DB.
mysqldump -u [username] -p [password] [databasename] > [backupfile.sql]
Then purge MySQL or follow the guide on how to reset your root password
After you have access to the DB again if you purged MySQL use this to bring your data back in.
mysqldump -u [username] -p [password] [databasename] < [backupfile.sql]
If you only lost your password to IcingaWeb2 or now have access to MySQL then create a MD5 based BSD password algorithm:
openssl passwd -1 "password"
Note: The switch to openssl passwd is the number one (-1) for using the MD5 based BSD password algorithm.
Insert the user into the database using the generated password hash:
````
INSERT INTO icingaweb_user (name, active, password_hash) VALUES ('icingaadmin', 1, 'hash from openssl');
Source

Table 'DBName.user' doesn't exist when trying to change root user name

I have just installed MySQL on Debian 7.0.0.
I successfully imported by database from another system using
mysql -u root -p DBName <mysql27May13.dump
I then successfully logged onto MySQL using
mysql -u root -p
I then successfully selected the database using
use DBName;
Also
show tables;
showed the tables I imported. However, when I try to change the root user name using
update user set user='SomeNewName' where user='root';
I get the error message
ERROR 1146 (42S02): Table 'DBName.user' doesn't exist
If you want to change a MySQL username you should use RENAME USER
RENAME USER root#localhost TO other_user#localhost
The table you want to update -- user, in this case -- is not within your database (which I assume is called DBName, here). The database you need is, in fact, simply called mysql.
You can work around this in a few ways:
Run your update on mysql.user instead of user.
use mysql before you do the update.
Use the supplied RENAME keyword to do the job instead, as #ExplosionPills suggests.
I'd suggest always taking approach #3 for user management unless you know for sure you're trying to do something the built-in commands can't handle. Chances are, you're not -- and if you are, you'll know it.

can't create database by xampp mysql command window

When I try to create a new database(m) in xampp mysql command window then I'm getting an error message
"ERROR 1044 (42000): Access denied for user ''#'localhost' to database
'm'".
Then I created that database by using phpmyadmin but its not shown in mysql command window when I type show databases command there. Can anybody tell me how can I get rid of that error message and can successfully create new database by using mysql command window in xampp? (I'm using windows xp professional service pack-2)
-Thanks.
Are you logging as a root?
Browse to the mysql.exe containing foler and try typing this in the cmd:
mysql.exe -u root --password
Try to initiate your mysql client with a specific username and password ( if you have set one )
mysql.exe -uroot [-p]
Edit:
Add this to your my.cnf [client] section to log-in without any parameter
[client]
user=root
http://dev.mysql.com/doc/refman/5.5/en/mysql-command-options.html
RESOLVED:** Thanks to all for your kind replies. I solved that problem.
I changed the 'user' table in 'mysql' database by using phpmyadmin and set the fields to 'Y' while those were 'N' where host was 'localhost'(so localhost wasn't able to create or drop any database).Now its possible to create new database by 'xampp\mysql\bin\mysql.exe'.
AND **to get .frm(table definition), .MYD(table data) and .MYI(table indices) files for a table in mysql data folder,I SET type=MyISAM and collation=utf8_general_ci so it would be easy to copy the database to another pc or server.
I know you've solved the problem .I had the same problem ,but the answer is simple .Answer :if you type "localhost" in your browser ,after selecting the language , you can select "phpmyadmin" .then as you said you can click on the "Databases" tab ,then from the list of databases select "mysql" and eventually you can see that the last table of this database is "user" table.if you then click on the "browse" button right in front of the name of the table which is "user". now you can see the "user" table in detail.you can see under the "host" column there are 3 "localhost" cells ,but only one of them has value of "root" in the "user"
column which is the next .so if you want to connect mysql via command prompt , if you have not set password yet ,( c:\xampp\mysql\bin\mysql.exe -u root ) not
( c:\xampp\mysql\bin\mysql.exe ) or not ( c:\xampp\mysql\bin\mysql.exe -u root -p ) .

How do i backup database data, so that it fits in a new database structure?

I have one local server where i work on my project, and i have another test server where i deploy the project.
Case:
I want to transfer the new database structure from the local server to the test server, and keep the data that already was on the test server database.
I tried to do this:
Backup the test server data by:
mysqldump –u USER –p –no-create-info DATABASE < OUTPUTFILE.sql
Then transfer the new structure to the test server, and then:
mysql –u USER –p –h localhost DATABASE < OUTPUTFILE.sql
to get all the data back.
The problem is this:
The table i have altered looks like this:
(local) -------------------------------(test server)
TABLENAME--------------------- TABLENAME
id ------------------------------------------id
name ------------------------------------name
active
So when i try to insert the old data to the new structure i get the errormessage:
ERROR 1136 (21S01) at line 17: Column count doesn't match value count at row 1
since it is trying:
INSERT INTO `TABLENAME` VALUES (1,"test")
Anyone got an idea of what i can do to solve this problem?
Thank you in advance
This is done in the commandline, but could ofcourse be done using mysql:
The solution is to first backup the data on the test server, so that it create full insert statements:
mysqldump –u USER –p PASSWORD --no-create-info --complete-insert DATABASE > BACKUPFILEData.sql
Then i backup the new structure of the local database:
mysqldump –u USER –p PASSWORD --no-data DATABASE > BACKUPFILEStructure.sql
Now that i have a backup of the old data, and the structure, i can insert the structure in the test server databbase:
mysql –u USER –p Password –h localhost DATABASE < BACKUPFILEStructure.sql
And finally we need to insert the old data again:
mysql –u USER –p Password –h localhost DATABASE < BACKUPFILEData.sql
Voila!
The old data is back in the new db structure
I'd suggest you copy the database locally, alter the table so that it fits the destination layout, then dump the copy, drop it and load the dump on the destination server. As an alternative, you could switch to dumping tables instead of the whole database, not dump the problematic table and use the copy/alter/dump/load for just this one table.

How do I retrieve my MySQL username and password?

I lost my MySQL username and password. How do I retrieve it?
Stop the MySQL process.
Start the MySQL process with the --skip-grant-tables option.
Start the MySQL console client with the -u root option.
List all the users;
SELECT * FROM mysql.user;
Reset password;
UPDATE mysql.user SET Password=PASSWORD('[password]') WHERE User='[username]';
But DO NOT FORGET to
Stop the MySQL process
Start the MySQL Process normally (i.e. without the --skip-grant-tables option)
when you are finished. Otherwise, your database's security could be compromised.
Unfortunately your user password is irretrievable. It has been hashed with a one way hash which if you don't know is irreversible. I recommend go with Xenph Yan above and just create an new one.
You can also use the following procedure from the manual for resetting the password for any MySQL root accounts on Windows:
Log on to your system as Administrator.
Stop the MySQL server if it is running. For a server that is running as a Windows service, go to
the Services manager:
Start Menu -> Control Panel -> Administrative Tools -> Services
Then find the MySQL service in the list, and stop it. If your server is
not running as a service, you may need to use the Task Manager to force it to stop.
Create a text file and place the following statements in it. Replace the password with the password that you want to use.
UPDATE mysql.user SET Password=PASSWORD('MyNewPass') WHERE User='root';
FLUSH PRIVILEGES;
The UPDATE and FLUSH statements each must be written on a single line. The UPDATE statement resets the password for all existing root accounts, and the FLUSH statement tells the server to reload the grant tables into memory.
Save the file. For this example, the file will be named C:\mysql-init.txt.
Open a console window to get to the command prompt:
Start Menu -> Run -> cmd
Start the MySQL server with the special --init-file option:
C:\> C:\mysql\bin\mysqld-nt --init-file = C:\mysql-init.txt
If you installed MySQL to a location other than C:\mysql, adjust the command accordingly.
The server executes the contents of the file named by the --init-file option at startup, changing each root account password.
You can also add the --console option to the command if you want server output to appear in the console window rather than in a log file.
If you installed MySQL using the MySQL Installation Wizard, you may need to specify a --defaults-file option:
C:\> "C:\Program Files\MySQL\MySQL Server 5.0\bin\mysqld-nt.exe" --defaults-file="C:\Program Files\MySQL\MySQL Server 5.0\my.ini" --init-file=C:\mysql-init.txt
The appropriate --defaults-file setting can be found using the Services Manager:
Start Menu -> Control Panel -> Administrative Tools -> Services
Find the MySQL service in the list, right-click on it, and choose the Properties option. The Path to executable field contains the --defaults-file setting.
After the server has started successfully, delete C:\mysql-init.txt.
Stop the MySQL server, then restart it in normal mode again. If you run the server as a service, start it from the Windows Services window. If you start the server manually, use whatever command you normally use.
You should now be able to connect to MySQL as root using the new password.
An improvement to the most useful answer here:
1] No need to restart the mysql server
2] Security concern for a MySQL server connected to a network
There is no need to restart the MySQL server.
use FLUSH PRIVILEGES; after the update mysql.user statement for password change.
The FLUSH statement tells the server to reload the grant tables into memory so that it notices the password change.
The --skip-grant-options enables anyone to connect without a password and with all privileges. Because this is insecure, you might want to
use --skip-grant-tables in conjunction with --skip-networking to prevent remote clients from connecting.
from: reference: resetting-permissions-generic
Do it without down time
Run following command in the Terminal to connect to the DBMS (you need root access):
sudo mysql -u root -p;
run update password of the target user (for my example username is mousavi and it's password must be 123456):
UPDATE mysql.user SET authentication_string=PASSWORD('123456') WHERE user='mousavi';
at this point you need to do a flush to apply changes:
FLUSH PRIVILEGES;
Done! You did it without any stop or restart mysql service.
While you can't directly recover a MySQL password without bruteforcing, there might be another way - if you've used MySQL Workbench to connect to the database, and have saved the credentials to the "vault", you're golden.
On Windows, the credentials are stored in %APPDATA%\MySQL\Workbench\workbench_user_data.dat - encrypted with CryptProtectData (without any additional entropy). Decrypting is easy peasy:
std::vector<unsigned char> decrypt(BYTE *input, size_t length) {
DATA_BLOB inblob { length, input };
DATA_BLOB outblob;
if (!CryptUnprotectData(&inblob, NULL, NULL, NULL, NULL, CRYPTPROTECT_UI_FORBIDDEN, &outblob)) {
throw std::runtime_error("Couldn't decrypt");
}
std::vector<unsigned char> output(length);
memcpy(&output[0], outblob.pbData, outblob.cbData);
return output;
}
Or you can check out this DonationCoder thread for source + executable of a quick-and-dirty implementation.
If you have root access to the server where mysql is running you should stop the mysql server using this command
sudo service mysql stop
Now start mysql using this command
sudo /usr/sbin/mysqld --skip-grant-tables --skip-networking &
Now you can login to mysql using
sudo mysql
FLUSH PRIVILEGES;
SET PASSWORD FOR 'root'#'localhost' = PASSWORD('MyNewPass');
Full instructions can be found here http://www.techmatterz.com/recover-mysql-root-password/
Login MySql from windows cmd using existing user:
mysql -u username -p
Enter password:****
Then run the following command:
mysql> SELECT * FROM mysql.user;
After that copy encrypted md5 password for corresponding user and there are several online password decrypted application available in web. Using this decrypt password and use this for login in next time.
or update user password using flowing command:
mysql> UPDATE mysql.user SET Password=PASSWORD('[password]') WHERE User='[username]';
Then login using the new password and user.
After MySQL 5.7.6 and MariaDB 10.1.20 (currently in 2022) you can:
Update a mysql user password having access to root user
ALTER USER 'some_user_name'#'localhost' IDENTIFIED BY 'a_super_secure_password';
Update mysql root user
ALTER USER 'root'#'localhost' IDENTIFIED WITH mysql_native_password by 'mynewpassword';
List all users
select user from mysql.user;
IF you happen to have ODBC set up, you can get the password from the ODBC config file. This is in /etc/odbc.ini for Linux and in the Software/ODBC folder in the registry in Windows (there are several - it may take some hunting)
Save the file. For this example, the file will be named C:\mysql-init.txt.
it asking administrative permisions for saving the file
Although a strict, logical, computer science'ish interpretation of the op's question would be to require both "How do I retrieve my MySQL username" and "password" - I thought It might be useful to someone to also address the OR interpretation. In other words ...
1) How do I retrieve my MySQL username?
OR
2) password
This latter condition seems to have been amply addressed already so I won't bother with it. The following is a solution for the case "How do i retreive my MySQL username" alone. HIH.
To find your mysql username run the following commands from the mysql shell ...
SELECT User FROM mysql.user;
it will print a table of all mysql users.