I have date in string format like "14-12-2012". After converting the date from string to date it is giving like this "#12/14/2012#"
Then I am trying to save date in database it is giving error.
Dim queryString As String = "UPDATE [ARIBA_CUST_ADMIN] SET [CUST_CRED_ID] = '" + eCustomer.CUST_CRED_ID + "',[CUST_NAME] = '" + eCustomer.CUST_NAME + "',[STREET1] = '" + eCustomer.STREET1 + "',[STREET2] = '" + eCustomer.STREET2 + "',[CITY] = '" + eCustomer.CITY + "',[State] = '" + eCustomer.STATE + "',[POSTAL_CD] = '" + eCustomer.POSTAL_CD + "',[COUNTRY] = '" + eCustomer.COUNTRY + "',[CUST_CRED_DOMAIN] = '" + eCustomer.CUST_CRED_DOMAIN + "',[SUBCHARGE] = '" + eCustomer.SUBCHARGE + "',[TAX_AT_LINE] = '" + eCustomer.TAX_AT_LINE + "',[PO_FLIP] = '" + eCustomer.PO_FLIP + "',[STATUS] = '" + eCustomer.STATUS + "',[CONFIMRATIONS] = '" + eCustomer.CONFIMRATIONS + "',[SHOP_NOTICES] = '" + eCustomer.SHOP_NOTICES + "',[INVOICE_TYPE] = '" + eCustomer.INVOICE_TYPE + "',[EFFECTIVE_DATE] = " + eCustomer.EFFECTIVE_DATE + ",[DISTRIBUTION_XML] = '" + eCustomer.DISTRIBUTION_XML + "' WHERE [CUST_ID] = " + eCustomer.CUST_ID
Dim dateString, format As String
Dim result As Date
Dim provider As Globalization.CultureInfo = Globalization.CultureInfo.InvariantCulture
' Parse date and time with custom specifier.
dateString = "20121216"
format = "yyyyMMdd"
result = Date.ParseExact(dateString, format, provider)
This will output the date in whatever format you specify in the format variable.
For the date format you want you'd use:
format = "dd-MM-yyyy"
You should use a parameterised query then you don't need to worry about the specific format, you just pass a date as the parameter (Assuming your DB column is a date type - it should be if it isn't):
Something along these lines
Dim d as Date= new Date(2012, 12, 3)'or ParseExact from a string in a known format
Dim sql As String = "INSERT INTO foo (DateValue) VALUES (#DateValue)"
Using cn As New SqlConnection("Your connection string here"), _
cmd As New SqlCommand(sql, cn)
cmd.Parameters.Add("#DateValue", SqlDbTypes.Date).Value = d
cmd.ExecuteNonQuery
End Using
Have a look at this question for more info
Related
my ideas: i select id(max) in table users to write table Userlogin. I get error:
'Conversion failed when converting the varchar value to data type int.'
SELECT idUser
FROM Users
WHERE idUser = (SELECT MAX(idUser) FROM Users)
how to fix error? thank you.
img error: Mycode, Myerror
mycode:
`` `using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
namespace Web_tintuc2
{
public partial class DangKi : System.Web.UI.Page
{
private string connectString = #"Data Source=DESKTOP-
RT3QMVS; Initial Catalog =web_tintuc; Integrated Security=True;";
SqlConnection sql_connect;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btn_thoat_Click(object sender, EventArgs
e)
{
Response.Redirect("Trangchu.aspx");
//Response.Write("<script>alert('Hello');</script>");
}
protected void btn_dangki_Click(object sender, EventArgs
e)
{
sql_connect = new SqlConnection(connectString);
sql_connect.Open();
string username = txt_username.Text;
string phone = txt_Phone.Text;
string password = txt_password.Text;
string name = txt_name.Text;
string ngaysinh = txt_brithday.Text;
string diachi = txt_diachi.Text;
string email = txt_Email.Text;
DateTime aDateTime = DateTime.Now;
string ngaydangki = aDateTime.ToString("yyyy-MM-dd HH:mm:ss"); // fomat kiểu ngày thánh trong sql server
string active = "Actived";
string IdGruop = "2";
string gioitinh1 = "Nam";
String gioitinh2 = "Nữ";
string sql_check = "select Username from Userlogin
where Username='" + username + "' ";
SqlCommand sql1 = new SqlCommand(sql_check,
sql_connect);
SqlDataReader read = sql1.ExecuteReader();
if (read.Read() == true)
Lb_thongbao.Text = "Username đã tồn tại";
read.Close();
if (Radio_nam.Checked == true)
{
string sql_insert_toUser = " insert into Users(HoTen,Diachi,Email,Dienthoai,gioitinh,ngaysinh,idGroup,ngaydangki,active ) values('" + name + "','" + diachi + "','" + diachi + "','" + email + "','" + phone + "','" + gioitinh1 + "','" + ngaysinh + "','" + IdGruop + "','" + ngaydangki + "','" + active + "')";
SqlCommand sqlcommand1 = new
SqlCommand(sql_insert_toUser, sql_connect);
sqlcommand1.ExecuteNonQuery();
string sql_id_users = "Select top 1 idUser from
Users order by idUser desc";
string sql_insert_to_UserLogin = "insert into
Userlogin(Username,Password,idUser) values('" + username + "','" +
password + "','" + sql_id_users + "') ";
SqlCommand sqlCommand2 = new
SqlCommand(sql_insert_to_UserLogin, sql_connect);
sqlCommand2.ExecuteNonQuery();
}
else if (Radio_nu.Checked == true)
{
string sql_insert_toUser = " insert into Users(HoTen,Diachi,Email,Dienthoai,gioitinh,ngaysinh,idGroup,ngaydangki,active )values('" + name + "','" + diachi + "','" + email + "','" + phone + "','" + gioitinh2 + "','" + ngaysinh + "','" + IdGruop + "','" + ngaydangki + "','" + active + "')";
SqlCommand sqlcommand1 = new SqlCommand(sql_insert_toUser, sql_connect);
sqlcommand1.ExecuteNonQuery();
string sql_id_users = " SELECT idUser FROM Users
WHERE idUser = (SELECT MAX(idUser) FROM Users) ";
string sql_insert_to_UserLogin = "insert into
Userlogin(Username,Password,idUser) values('" + username + "','" +
password + "','"+sql_id_users+"') ";
SqlCommand sqlCommand_2 = new
SqlCommand(sql_insert_to_UserLogin, sql_connect);
sqlCommand_2.ExecuteNonQuery();
}
}
}
}'' '
Your error is coming from your insert statement (line 62). You have single quotes around the variable sql_id_users. Remove the single quotes. It's treating the value as varchar since you have it enclosed in single quotes but it expects an integer.
Suggestion: When you post, please post your code as text and not an image.
I am getting android.database.sqlite.SQLiteException "SELECTamountFROMnilanjan_tableWHEREName": syntax error (code 1):
public Cursor getItemID(String name)
{
SQLiteDatabase db =this.getWritableDatabase();
String query = "SELECT" + COL_3 + "FROM" + TABLE_NAME +"WHERE" + COL_2 + " = '" + name + "'" ;
Cursor data = db.rawQuery(query,null);
return data;
}
"SELECTamountFROMnilanjan_tableWHEREName" from your error message is the result of your concatination to be executed as query.
you need to add spaces between your keywords to create a valid query.:
"SELECT " + COL_3 + " FROM " + TABLE_NAME + " WHERE " + COL_2 + " = '" + name + "'" ;
I have users form in which they can select some values from checkbox list & values selected in that stores in database in li form. Now I want when users wants to update their form they should be able to see the values checked they have selected earlier.
here is my code.
Insert Form
Private Sub PopulateServices()
Using conn As New MySqlConnection()
conn.ConnectionString = ConfigurationManager _
.ConnectionStrings("conio").ConnectionString()
Using cmd As New MySqlCommand()
cmd.CommandText = "select * from services"
cmd.Connection = conn
conn.Open()
Using sdr As MySqlDataReader = cmd.ExecuteReader()
While sdr.Read()
Dim item As New ListItem()
item.Text = sdr("serviceName").ToString()
item.Value = sdr("serviceName").ToString()
'item.Selected = Convert.ToBoolean(sdr("IsSelected"))
servicesList.Items.Add(item)
End While
End Using
conn.Close()
End Using
End Using
End Sub
Dim selectedServices As String = String.Empty
For Each chk As ListItem In servicesList.Items
If chk.Selected = True Then
selectedServices &= "<li>" + chk.Text + "</li>"
End If
Next
Try
Dim str1 As String = "INSERT INTO hospitals (`hospitalID`,`username`, `password`) values ('" + ID + "', '"selectedServices.ToString + "', '" + mobileNumber + "', '" + membersAutoPassword.Text + "')"
Dim str2 As MySqlDataReader
Dim adapter As New MySqlDataAdapter
Dim command As New MySqlCommand
command.CommandText = str1
command.Connection = con
adapter.SelectCommand = command
con.Open()
str2 = command.ExecuteReader
con.Close()
Response.Redirect("business-added.aspx")
Catch ex As Exception
Response.Write(ex)
End Try
On User Profile page after login they should be able to see what options they have selected. Hence there is a option for users to update their details again
UPDATED
User Profile Page
Private Sub list_business_hospital_Load(sender As Object, e As EventArgs) Handles Me.Load
If Not IsPostBack Then
Try
Dim str As String = "SELECT * FROM hospitals WHERE username='" + Server.HtmlEncode(Request.Cookies("chkusername").Value) + "';"
con.Open()
Dim cmd As New MySqlCommand(str, con)
Dim da As New MySqlDataAdapter(cmd)
Dim dt As New DataTable
Dim lblservice As New Label
For Each chk As ListItem In servicesList.Items
If chk.Selected = True Then
lblservice.Text = String.Concat(lblservice.Text + ",", chk.Value)
End If
Next
da.Fill(dt)
con.Close()
TextId.Text = dt.Rows(0)("hospitalID").ToString
Catch ex As Exception
Response.Write(ex)
End Try
Private Sub PopulateServices()
Using conn As New MySqlConnection()
conn.ConnectionString = ConfigurationManager _
.ConnectionStrings("conio").ConnectionString()
Using cmd As New MySqlCommand()
cmd.CommandText = "select * from services"
cmd.Connection = conn
conn.Open()
Using sdr As MySqlDataReader = cmd.ExecuteReader()
While sdr.Read()
Dim item As New ListItem()
item.Text = sdr("serviceName").ToString()
item.Value = sdr("serviceName").ToString()
'item.Selected = Convert.ToBoolean(sdr("IsSelected"))
servicesList.Items.Add(item)
End While
End Using
conn.Close()
End Using
End Using
End Sub
Private Sub updateInfo_Click(sender As Object, e As EventArgs) Handles updateInfo.Click
Try
Dim con As New MySqlConnection
Dim query As New MySqlCommand
con.ConnectionString = ConfigurationManager _
.ConnectionStrings("conio").ConnectionString()
query.Connection = con
con.Open()
Dim selectedServices As String = String.Empty
For Each chk As ListItem In servicesList.Items
If selectedServices.Contains("<li>" & chk.Text & "</li>") Then
'display item as selected
chk.Selected = True
End If
Next
query.CommandText = "UPDATE hospitals SET name = '" + businessName.Text + "', contactPerson = '" + contactPerson.Text + "', websiteName = '" + websiteName.Text + "', email = '" + emailName.Text + "', phone1 = '" + phone1.Text + "', phone2 = '" + phone2.Text + "', mobileNumber = '" + mobile.Text + "', buildingName = '" + buildingName.Text + "', streetName = '" + address.Text + "', landmark = '" + landmark.Text + "', areaName = '" + areaName.Text + "', city = '" + suburb.Text + "', state = '" + state.Text + "', zipCode = '" + zip.Text + "', overview = '" + overview.Text + "', registration = '" + regNo.Text + "', establishment = '" + foundation.Text + "', founder = '" + founderName.Text + "', generalBed = '" + GeneralBeds.Text + "', icuBed = '" + ICU.Text + "', consultancyFees = '" + consultinfees.Text + "', mondayFrom = '" + mondayFrom.Text + "', mondayTo = '" + mondayTo.Text + "', tuesdayFrom = '" + tuesdayFrom.Text + "', tuesdayTo = '" + tuesdayTo.Text + "', wednesdayFrom = '" + wedFrom.Text + "', wednesdayTo = '" + wedTo.Text + "', thursdayFrom = '" + thursdayFrom.Text + "', thursdayTo = '" + thursdayTo.Text + "', fridayFrom = '" + fridayFrom.Text + "', fridayTo = '" + fridayTo.Text + "', saturdayFrom = '" + saturdayFrom.Text + "', saturdayTo = '" + saturdayTo.Text + "', sundayFrom = '" + sundayFrom.Text + "', sundayTo = '" + sundayTo.Text + "', visitFrom = '" + visitFrom.Text + "', visitTo = '" + visitTo.Text + "', bestKnownFor = '" + bestknowFor.Text + "' WHERE hospitalID = '" + TextId.Text + "'"
query.ExecuteNonQuery()
con.Close()
Response.Write("<script language='javascript'>alert('Information updated successfully.');</script>")
Catch ex As Exception
Response.Write(ex)
End Try
End Sub
Please check below,
'Here I assume that, you will call PopulateServices to populate servicesList checkbox list
PopulateServices()
'You didn't mention fieldName, so I assume that field in database is :
'savedServices - This will be li tags like, <li>item 1</li><li>item 2</li>
'Now loop through all items within checkbox list
For Each chk As ListItem In servicesList.Items
'You need to check whether this item saved in database or not?
'If item already saved in database, display as selected
If savedServices.Contains("<li>" & chk.Text & "</li>") Then
'display item as selected
chk.selected = true
End If
Next
the date in excel is of the date time format and the selected date is also date time format but wots the problem
OleDbDataAdapter da1 = new OleDbDataAdapter("SELECT [ProjectId],[ProjectName],[ManagerID],[ManagerName],[AllocationStartDate],[AllocationEndDate],[horizontalshortname] FROM [" + getExcelSheetName + #"] where [horizontalshortname]="+ "'" + TextBox_Horizontal.Text + "'"
+ " AND [Isonsite]=" + "'" + DropDownList_Location.SelectedItem.Text + "'"
+ " AND [AllocationStartDate]>="+Calendar1.SelectedDate
+ " AND [AllocationEndDate]<="+Calendar2.SelectedDate
, conn);
DataSet ds1 = new DataSet();
da1.Fill(ds1);
//if (ds.Tables[0] != null )
if (ds1.Tables[0].Rows.Count > 0)
{
GridView_Utilization_Search.Visible = true;
GridView_Utilization_Search.DataSource = ds1.Tables[0];
GridView_Utilization_Search.DataBind();
}
else
{
GridView_Utilization_Search.Visible = false;
}
I get an error "ORA-00947: not enough values") inserting a record and can't see why! It seems to me I have the correct number of parameters:
string sQuery = "insert into EventLog (UserEventLogID, USERID, EVENTSEVERITYID, LOGTIME_TZ, USEREVENTTYPEID, USEREVENTMSG) " +
"values (0, :USERID, :EVENTSEVERITYID, cast(:LOGTIME_TZ as Timestamp(6) With Time Zone) at time zone '" + oLog.TimeZone + "'), " +
":EVENTTYPEID, :EVENTMSG) " +
" returning USEREVENTLOGID into :EventLogID";
oraCmd = new OracleCommand();
oraCmd.BindByName = true;
oraCmd.Parameters.Add("EVENTSEVERITYID", OracleDbType.Int16, 2, oLog.EventSeverityID, ParameterDirection.Input);
oraCmd.Parameters.Add("LOGTIME_TZ", OracleDbType.TimeStamp, 6, oLog.EventTimestamp, ParameterDirection.Input);
oraCmd.Parameters.Add("EVENTTYPEID", OracleDbType.Int16, 4, oLog.EventTypeID, ParameterDirection.Input);
oraCmd.Parameters.Add("EVENTMSG", OracleDbType.Varchar2, 300, oLog.EventMsg, ParameterDirection.Input);
oraCmd.Parameters.Add("USERID", OracleDbType.Varchar2, 50, oLog.UserID, ParameterDirection.Input);
outParam = new OracleParameter("EventLogID", OracleDbType.Decimal);
outParam.Direction = ParameterDirection.Output;
oraCmd.Parameters.Add(outParam);
the table has one more column "LGTIME" which is nullable so I did not include it in insert statement.
I see an extra ")" .
cast(:LOGTIME_TZ as Timestamp(6) With Time Zone) <----- at time zone '" + oLog.TimeZone + "')